Search code examples
cmemoryallocation

Retaining C memory throughout the function


Assuming I have a piece of code similar to this:

SOMESTRUCTURE *info;
info = malloc(sizeof(SOMESTRUCTURE));

while(something...)
{
     info->mini[0] = malloc(sizeof(SOMESTRUCTURE *)); // It's a structure inside the same structure
     while(something...)
     {
           info->mini[x]->name = malloc(sizeof(char *)*strlen(name));
           printf("%s\n", info->mini[0]->name); // This prints out the correct value
     }
}

printf("%s\n", info->mini[0]->name); // But now the value is lost and is null

How can I make the info->mini[0]->name value apply throughout the entire function?


Solution

  • No, that should still be available to you. The only way you could lose the value would be if x were 0 on one of the iterations of your while loop or if you execute the malloc inside the outer loop without entering the inner loop - it's hard to tell if this is possible since you don't specify what something is in both cases.

    It's true that variable created within a certain scope will disappear when you exit that scope but that isn't the case here. Allocated memory will survive scope changes. A given pointer to that memory may not but your pointer in this case (info is still in scope when you exit the outer while statement).

    I do see one other potential problem - your malloc(sizeof(char *) * strlen(name)) should probably be malloc(strlen(name) + 1) (since sizeof(char) is always 1). It probably works because a char * will normally be bigger than a char but it's the wrong way to do it nonetheless.

    However, I cannot see anywhere in your code where you actually set info->mini[0]->name to anything so I'm at a loss as to how it can ever have a correct value, unless it's somehow picking up a value from a previous malloc (this is possible since malloc itself is not required to clear the memory it gives to you).

    You should post your actual code or preferably the smallest piece of code that exhibits the problem.