简体   繁体   中英

Limitations of malloc / realloc to char **?

Say I have a char** "bob" which I malloc in the form of

char **bob = malloc(10 * sizeof(bob[0]));

And say for every element I store under bob, I malloc a certain amount of space in the form of

bob[num] = malloc(10);

My question is, can you only malloc elements under bob up to the amount you've malloced the char** itself?

Ie if bob[num] = malloc(10); is repeated 5 times, we've malloced 50 bytes in total - since that exceeds the original 10 * sizeof(bob[0]) (which mallocs 40), does this cause the program to screw up?

Or is the amount of memory you malloc to elements under the char** not restricted by the memory allocated to char** itself?

Or is the amount of memory you malloc to elements under the char** not restricted by the memory allocated to char** itself?

Yes, this is the case. When you allocate memory for your char** , you're making room for 10 char* 's. When you then allocate these char* 's, they end up pointing up to completely separate, new blocks of memory, unrelated to the block in which they themselves are stored.

You are creating a pointer-based look-up table. Don't confuse this for a 2D array.

The first malloc allocates an array of pointers, the actual table, which has no relation what-so-ever to the pointed at data. The memory layout will be like this:

bob[0] -> some segment of memory
bob[1] -> some other segment of memory
...

The sizes of the different segments could also be completely individual with no relation to each other.

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