verifying
verifying

Reputation: 131

Local Struct Variables vs Assignement of Structs

Consider the following code:

#include <malloc.h>

typedef struct{
    int a;
    int* b; 
} test; 

void foo(test* t){
    test u = {.a = 1; .b = (test*) malloc(3*sizeof(test))}
    u.b[0]=0;
    u.b[1]=1;
    u.b[2]=2;
    *t=u; 
}

void main(){
    test t;
    foo(&t);
}

The variable u is local to the function foo.

My question is: What happens with the variables u and t after the function foo is executed?

1. Is the memory allocated for u.a released? 
2. Is the memory allocated for u.b freed?
3. Is t.b equal to the vector [0,1,2]?

Upvotes: 0

Views: 55

Answers (1)

bruno
bruno

Reputation: 32596

What happens with the variables u and t after the function foo is executed?

nothing with the code you give because it cannot compile for a lot of reasons :

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall c.c
c.c: In function ‘foo’:
c.c:7:21: error: expected ‘}’ before ‘;’ token
     test u = {.a = 1; .b = (test*) malloc(3*sizeof(test))}
                     ^
c.c:8:5: error: expected ‘,’ or ‘;’ before ‘u’
     u.b[0]=0;
     ^
c.c:11:6: error: incompatible types when assigning to type ‘test * {aka struct <anonymous> *}’ from type ‘test {aka struct <anonymous>}’
     t=u;
      ^
c.c:6:16: warning: parameter ‘t’ set but not used [-Wunused-but-set-parameter]
 void foo(test* t){
                ^
c.c: At top level:
c.c:14:6: warning: return type of ‘main’ is not ‘int’ [-Wmain]
 void main(){
      ^~~~
c.c: In function ‘main’:
c.c:16:9: error: incompatible type for argument 1 of ‘foo’
     foo(t);
         ^
c.c:6:6: note: expected ‘test * {aka struct <anonymous> *}’ but argument is of type ‘test {aka struct <anonymous>}’
 void foo(test* t){
      ^~~

A corrected version of the code is :

#include <malloc.h>

typedef struct{
    int a;
    int* b; 
} test; 

void foo(test* t){
    test u = {.a = 1, .b = (int*) malloc(3*sizeof(test))};
    u.b[0]=0;
    u.b[1]=1;
    u.b[2]=2;
    *t=u; 
}

int main(){
    test t;
    foo(&t);
}

Using the corrected version :

  1. Is the memory allocated for u.a freed?

u is a local variable, it is not allocated in the heap but placed in the stack, after returning from foo the local variable does not exist anymore, so the same for the field u.a

  1. Is the memory allocated for u.b freed?

the memory allocated by malloc whose pointer was saved in u.b is not freed, but the memory used for u.b is in the stack as for u.a or u itself so after the return that fields does not exist anymore

  1. Is t.b equal to the vector [0,1,2]?

yes after the correction copying deeply, t.b in main points to the array allocated by malloc then set in foo

if you add printf("%d %d %d\n", t.b[0], t.b[1], t.b[2]); at the end of main it will print 0 1 2

Upvotes: 2

Related Questions