【发布时间】:2014-12-14 06:53:31
【问题描述】:
我在使用 realloc 打开内存时遇到问题。我正在尝试为从文件中读取的字符串数组动态分配内存。我想要做的是,使用 fgets 读取一行的前 200 个字符,如果这 200 个字符有新行,我继续下一行。我有这个工作得很好而且花花公子。我的问题是当前 200 个字符没有换行符时,我试图将另外 200 个字符的空间重新分配给字符串,然后将新的 200 个字符连接到旧的字符上,直到它包含一个新行。经测试,在第二个realloc上出现glibc error of invalid size。
我调用 realloc 是不是错了?我已经阅读了手册页并将其用作参考,而我用作参考的书说因为它是 sizeof(char) ,所以我不需要实际包含其大小。谁能指出我哪里出错了?非常感谢您的帮助。
while( (!feof(file)) && lineCount < 11999 ) { //will loop til end of file
lines[index] = malloc(201*sizeof(char)); //give 201 spaces for the pointer at index
fgets(lines[index], 200, file); //gets first 200 chars
temp = strchr(lines[index], '\n'); //set temp for while loop
while(temp == NULL){ //while the string doesnt have \n
printf("string doesn't have have a newline character\n");
lines[index]=realloc(lines[index],200); //lines[index] now has 200 extra space
printf("added extra space\n");
fgets(temp2,200,file); //read next 200 chars into temp
printf("%s",temp2); //for testing print next 200 lines
temp=strchr(temp2,'\n'); //for while loop, check if temp has "\n"
strcat(lines[index],temp2); //concat string onto end
printf("This is lines after cat\n\n\n%s",lines[index]); //testing print
}//variables are iterated here
}
再次感谢您的时间和帮助。
编辑:在下面回答
【问题讨论】:
-
您的
realloc()电话使您的分配更小,而不是更大。 -
如果你的尺寸总是
200,那么realloc()ating 有什么意义?不是要重新分配给(previous size) + 200吗?您阅读realloc()的文档了吗? -
realloc()的大小参数是新的总大小,而不是大小的增量或减量。 -
啊啊啊啊!!!谢谢,手册页有一个设置大小的增加,而不是增量增加!这太有道理了!!!请将您的评论作为答案,以便我标记为正确!
-
@ChristopherJordan “手册页有它可以增加设置的大小”——我简直不敢相信。您正在阅读哪个手册页,具体而言?您更可能误解了手册页的措辞。