Home Forums HCL Reviews Tutorials Articles Register Search Today's Posts Mark Forums Read
 LinuxQuestions.org how to free this structure
 Programming This forum is for all programming questions. The question does not have to be directly related to Linux and any language is fair game.

Notices

 05-07-2008, 06:41 AM #1 carlcs LQ Newbie   Registered: Apr 2008 Posts: 14 Rep: how to free this structure typedef struct{ int a; char *b; }A; typedef struct{ int c; char *d; A *A1; }B; B *B1; B1 = malloc(sizeof(B)); A1 = malloc(sizeof(A)); d = malloc(100); b = malloc(10); how to free , is the structure need a for loop to free?
05-07-2008, 07:09 AM   #2
jf.argentino
Member

Registered: Apr 2008
Location: Toulon (France)
Distribution: FEDORA CORE
Posts: 492

Rep:
Quote:
 B1 = malloc(sizeof(B));
you just get the place to keep two pointers, one on a character, and the other on a A struct. But you haven't reserved the room for the embedded A struct! So make something like "B1->A1->a = 10" IS AN ERROR, you have to
Code:
```B1 = malloc(sizeof(B));
A* A1 = malloc (sizeof (A));
B1->A1 = A1;```
or directly, if you prefer,
Code:
```B1 = malloc(sizeof(B));
B1->A1 = malloc (sizeof (A));```
Same comments for the other structure fields

05-07-2008, 11:15 PM   #3
carlcs
LQ Newbie

Registered: Apr 2008
Posts: 14

Original Poster
Rep:
Thank you for pointing my error. Now I allocate like below
Quote:
 B1 = malloc(sizeof(B)); B1->A1 = malloc (sizeof (A));
how do i free them if i allocate b and d
Quote:
 d = malloc(100); b = malloc(10);

Is the structure need a for loop to free?

 05-09-2008, 02:45 AM #4 jf.argentino Member   Registered: Apr 2008 Location: Toulon (France) Distribution: FEDORA CORE Posts: 492 Rep: Pointers are only addresses. The address they point on can be allocated or not. What you've to understand from this sentence is that each "malloc" must have its only one "free" on the same address, which is not necessary the same pointers. With an example: Code: ```B1 = malloc(sizeof(B)); A* A1 = malloc (sizeof (A)); A1->b= malloc (100); B1->A1 = A1; /* B1->A1 and A1 are 2 different pointers on the same address */ char* e = malloc (sizeof (1000)); B1->d = e;``` You can un-allocate these with: free (A1->b); /* or free (B1->A1->b), but not the two */ free (A1); /* or free (B1->A1, but not the two) */ You can't freeing A1 then A1->b since after free (A1), the pointer A1->b doesn't exist anymore, but the address it points on is always allocated, it's a memory leak! For B1, you can free (B1) then free (e), or free (B1->d) then free (B1), but not free (B1), then free (B1->d).
 05-10-2008, 12:12 PM #5 carlcs LQ Newbie   Registered: Apr 2008 Posts: 14 Original Poster Rep: Thank you very much. I has been solved this problem.

 Tags free, structure