如何malloc char**表?
我正在尝试分配并释放一个由单字母字符串组成的小数组/表。我知道这可以在数组中完成,但我想尝试使用 malloc 和 free 来完成此操作。
我现在有这个:
char **letters = (char**) malloc(5 * sizeof(char*));
int i =0;
for(i=0; i < NUMLETTERS ; ++i )
{
letters[i] = (char*) malloc(2*sizeof(char)); //2 is for the letter and null terminator
}
letters[0] = "a";
letters[1] = "b";
letters[2] = "c";
letters[3] = "d";
letters[4] = "e";
//Do stuff here
int i =0;
for(i=0; i < 5; ++i )
{
free(letters[i]);
}
free(letters);
上面的代码编译得很好,我的代码也可以正常工作并运行良好,但在运行时它在空闲部分出现错误。另外,使用 valgrind 后...它说 free(letters[i]); 无效。
有什么帮助吗?
I am trying to malloc and free a small array/table of single letter strings. I know that this can be done in an array, but I want to try and do this with a malloc and free.
I have this right now:
char **letters = (char**) malloc(5 * sizeof(char*));
int i =0;
for(i=0; i < NUMLETTERS ; ++i )
{
letters[i] = (char*) malloc(2*sizeof(char)); //2 is for the letter and null terminator
}
letters[0] = "a";
letters[1] = "b";
letters[2] = "c";
letters[3] = "d";
letters[4] = "e";
//Do stuff here
int i =0;
for(i=0; i < 5; ++i )
{
free(letters[i]);
}
free(letters);
The above code compiles fine and my code in between also works and runs fine, but at runtime it gets an error during the free parts. Also, after using valgrind..it says that the free(letters[i]); is invalid.
Any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题就在这里:
您正在用字符串文字覆盖每个 malloc 的指针。然后你在最后的循环中释放它们。由于您有效地释放了字符串文字,因此它失败了。
有两种方法可以解决这个问题:
1:如果您只是将字符串文字分配给它们,则不需要内部分配。所以摆脱这两个循环。
2:用
strcpy
每个字符串文字来代替。The problem is here:
You are overwriting each of your malloc'ed pointers with string literals. Then you free them in the final loop. Since you are effectively freeing the string literals, it fails.
There are two ways to solve this:
1: You don't need the inner allocation if you are just assigning string literals to them. So get rid of both loops.
2:
strcpy
each of the string literals instead.您正在为数组中的每个字符串正确分配内存,但您没有使用该内存。相反,您将更改五个数组元素中每个元素中的
char*
指针,以指向字符串文字“a”、“b”、“c”等。因此,您丢失了对您分配的原始内存,而您却试图释放不属于您的内存。
不要像这样分配字符串指针:
您应该将字符串复制到您分配的内存中,如下所示:
You are correctly allocating memory for each string in the array, but then you aren't using that memory. You are instead altering the
char*
pointers in each of the five array elements to point to the string literals "a", "b", "c", etc.So, you have lost the references to the original memory you allocated, and you are instead trying to free memory which doesn't belong to you.
Instead of assigning the string pointers like this:
you should be copying the string into the memory you've allocated, like this: