I have been working on the following code for a while and there is a problem when I tried to allocate/deallocate memory for a struct and its elements. Any insights into the problem would be greatly appreciated thanks. Looking at the error message, I believe the problem lies in the fact that I tried to free an element that I had not properly allocated memory for but it is not obvious to me while looking at the code. I also tried code where I did not individually allocate memory for each element of the struct but that did not work as well.
typedef struct {
char *cnet;
char *email;
char *fname;
char *lname;
char *tel;
} vcard;
vcard *vcard_new(char *cnet, char *email, char *fname, char *lname, char *tel)
{
vcard* new = (vcard*)malloc(sizeof(vcard));
printf("%lu\n", sizeof(new->tel) );
new->cnet = malloc(sizeof(new->cnet));
new->email = malloc(sizeof(new->email));
new->fname = malloc(sizeof(new->fname));
new->lname = malloc(sizeof(new->lname));
new->tel = malloc(sizeof(new->tel));
new->cnet = cnet;
new->email = email;
new->fname = fname;
new->lname = lname;
new->tel = tel;
return new;
}
/* vcard_free : free vcard and the strings it points to
*/
void vcard_free(vcard *c)
{
free(c->cnet);
free(c->email);
free(c->fname);
free(c->lname);
free(c->tel);
free(c);
return;
}
sizeof(new->cnet)
= size of a pointer, and I seriously suspect that is not intentional. Rinse/repeat for every allocation in that function Not that it matters much, since you leak all of those allocations later in the same function. Assignment operators are not how strings are copied in C; it's how values are copied, and in this case, they're the values of pointers. A good C text and the section on strings, followed by the section on dynamic memory, will help immensely. – Thalassicnew
:-). – Quinnquinol