Structure pointer and memory management element

I am wondering what happens to a struct element that points to a non-dynamically distributed variable. So:

#include <stdio.h> #include <stdlib.h> typedef struct { int value; int *pointer; } MyStruct; int year = 1989; int main (int argc, const char * argv[]) { MyStruct *myStruct = (MyStruct *) malloc(sizeof(MyStruct)); myStruct->value = 100; myStruct->pointer = &year; year++; printf("%d \n", *myStruct->pointer); // what happens to the myStruct->pointer member when we free myStruct ? free(myStruct); return EXIT_SUCCESS; } 

I assume that it is destroyed, no longer indicates the year right? If so, would the same be true if * a pointer pointing to the correct function?

like this:

 typedef struct { int value; void (*someFunc)(); } MyStruct; 

Then later:

 void sayHi(){ printf("hi"); } ... myStruct->someFunc = sayHi; 

No special cleanup is required other than free () if our structure was created using malloc? Thanks for any information anyone has.

+4
source share
1 answer

If you are not malloc (or calloc/strdup/realloc ), you do not need to free it. Nothing special is required - the member variable just points to something, it does not logically "own" the pointy in memory.

Your year member variable will still exist and will be valid after you are free(myStruct) - myStruct->pointer will be invalid for use if

+7
source

Source: https://habr.com/ru/post/1347458/


All Articles