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?
No, that should still be available to you. The only way you could lose the value would be if
xwere 0 on one of the iterations of yourwhileloop or if you execute themallocinside the outer loop without entering the inner loop – it’s hard to tell if this is possible since you don’t specify whatsomethingis 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 (
infois still in scope when you exit the outerwhilestatement).I do see one other potential problem – your
malloc(sizeof(char *) * strlen(name))should probably bemalloc(strlen(name) + 1)(sincesizeof(char)is always 1). It probably works because achar *will normally be bigger than acharbut it’s the wrong way to do it nonetheless.However, I cannot see anywhere in your code where you actually set
info->mini[0]->nameto 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 previousmalloc(this is possible sincemallocitself 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.