如何正确地重新分配一系列字符串?
这似乎是一个简单的问题,可能是一个简单的答案,但是我试图用文本文件中的单词读取并将每个单词分配给动态分配的字符串:(
char** words = calloc(8, sizeof(char*));
必须通过这种方式分配。)
然后我必须调整大小的大小 。数组根据需要。当我尝试将realloc()
用于我的数组时,我的问题就出现了。我这样做:
if(index == MAX-1){ // reallocate if needed
words = (char**) realloc(words, sizeof(*words)*2); MAX*=2;
printf("Re-allocated %lu character pointers.\n", MAX);
}
其中最大值是可以存储在数组中的最大元素数。
我的阵列填充有正确的值,但是当Realloc称为一些字符串时,似乎丢失了一些字符串!几个索引不再填充了,当试图以某种方式打印数组时,我会遇到内存错误。
这是我分配字符串并将其存储在索引中的方式:
words[index] = malloc(strlen(temp)+1);
words[index] = strdup(temp); // copy the word over using strdup
出了什么问题?
This seems like a simple question and probably a simple answer but I am trying to read in words from a text file and allocate each word to a dynamically allocated array of strings:
char** words = calloc(8, sizeof(char*));
(It must be allocated this way.)
And then I must resize the array as needed. My problem comes when I try to use realloc()
for my array. I do it like so:
if(index == MAX-1){ // reallocate if needed
words = (char**) realloc(words, sizeof(*words)*2); MAX*=2;
printf("Re-allocated %lu character pointers.\n", MAX);
}
Where MAX is the max number of elements that can be stored in the array.
My array is populated with correct values but when realloc is called some strings appear to be missing! Several indexes are not populated anymore and I get a memory error when trying to print the array out as they are missing somehow.
Here is how I allocate the strings and store them at the index:
words[index] = malloc(strlen(temp)+1);
words[index] = strdup(temp); // copy the word over using strdup
What's going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于初学者,此代码片段
会产生内存泄漏。您应该立即编写
此语句
仅分配类型
char *
的两个指针。您应该至少
还要编写IF语句中的条件
,而不是
应该使用
max
的值,那么为什么使用Magic Number Number8
?For starters this code snippet
produces a memory leak. You should write at once
This statement
allocates only two pointers of the type
char *
.You should write at least
Also the condition in the if statement should be
instead of
And if you are using the value of
MAX
then why is there used the magic number8
?