简体   繁体   English

malloc / realloc对char **的限制?

[英]Limitations of malloc / realloc to char **?

Say I have a char** "bob" which I malloc in the form of 说我有一个char **“ bob”,我以以下形式分配

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下存储的每个元素,我都会以以下形式分配一定的空间:

bob[num] = malloc(10);

My question is, can you only malloc elements under bob up to the amount you've malloced the char** itself? 我的问题是,您能否仅将bob下的元素分配给您分配给char **本身的数量?

Ie if bob[num] = malloc(10); 即,如果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? 重复5次,我们总共分配了50个字节-由于超出了原来的10 * sizeof(bob[0]) (malloc分配了40个字节),这是否会使程序搞砸了?

Or is the amount of memory you malloc to elements under the char** not restricted by the memory allocated to char** itself? 还是您为char **下的元素分配的内存量不受分配给char **本身的内存的限制?

Or is the amount of memory you malloc to elements under the char** not restricted by the memory allocated to char** itself? 还是您为char **下的元素分配的内存量不受分配给char **本身的内存的限制?

Yes, this is the case. 是的,就是这种情况。 When you allocate memory for your char** , you're making room for 10 char* 's. 当为char**分配内存时,您将为10个char*腾出空间。 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. 然后,当您分配这些char* ,它们最终指向完全独立的新内存块,与它们本身存储的块无关。

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. 第一个malloc分配一个指针数组,即实际表,该指针表与所指向的数据没有任何关系。 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. 不同段的大小也可以完全独立,彼此无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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