简体   繁体   中英

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]?

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 ua 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 ua

  1. Is the memory allocated for ub freed?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM