我正在尝试从stdin读入(从文件传入值)。我正在从字符串中读取每个字符并将其存储到动态分配的字符串指针中。需要时我会重新分配内存。我想尽可能多地填充字符。虽然我可以将其限制为100,000个字符。但是在一些迭代之后realloc失败了。但是如果我在malloc的第一次初始化期间指定一个大块的大块,比如1048567,我就能完全读取该字符串。这是为什么?
以下是我的计划:
#include <stdio.h>
#include <stdlib.h>
int display_mem_alloc_error();
enum {
CHUNK_SIZE = 31 //31 fails. But 1048567 passes.
};
int display_mem_alloc_error() {
fprintf(stderr, "\nError allocating memory");
exit(1);
}
int main(int argc, char **argv) {
int numStr; //number of input strings
int curSize = CHUNK_SIZE; //currently allocated chunk size
int i = 0; //counter
int len = 0; //length of the current string
int c; //will contain a character
char *str = NULL; //will contain the input string
char *str_cp = NULL; //will point to str
char *str_tmp = NULL; //used for realloc
str = malloc(sizeof(*str) * CHUNK_SIZE);
if (str == NULL) {
display_mem_alloc_error();
}
str_cp = str; //store the reference to the allocated memory
scanf("%d\n", &numStr); //get the number of input strings
while (i != numStr) {
if (i >= 1) { //reset
str = str_cp;
len = 0;
curSize = CHUNK_SIZE;
}
c = getchar();
while (c != '\n' && c != '\r') {
*str = (char *) c;
//printf("\nlen: %d -> *str: %c", len, *str);
str = str + 1;
len = len + 1;
*str = '\0';
c = getchar();
if (curSize / len == 1) {
curSize = curSize + CHUNK_SIZE;
//printf("\nlen: %d", len);
printf("\n%d \n", curSize); //NB: If I comment this then the program simply exits. No message is displayed.
str_tmp = realloc(str_cp, sizeof(*str_cp) * curSize);
if (str_tmp == NULL) {
display_mem_alloc_error();
}
//printf("\nstr_tmp: %d", str_tmp);
//printf("\nstr: %d", str);
//printf("\nstr_cp: %d\n", str_cp);
str_cp = str_tmp;
str_tmp = NULL;
}
}
i = i + 1;
printf("\nlen: %d", len);
//printf("\nEntered string: %s\n", str_cp);
}
str = str_cp;
free(str_cp);
free(str);
str_cp = NULL;
str = NULL;
return 0;
}
感谢。
答案 0 :(得分:6)
当你realloc
str_tmp = realloc(str_cp, sizeof(*str_cp) * curSize);
if (str_tmp == NULL) {
display_mem_alloc_error();
}
//printf("\nstr_tmp: %d", str_tmp);
//printf("\nstr: %d", str);
//printf("\nstr_cp: %d\n", str_cp);
str_cp = str_tmp;
str_tmp = NULL;
你让str_cp
指向新的内存块,但str
仍指向旧的free
d块。因此,当您访问下一次迭代中str
指向的内容时,您将调用未定义的行为。
您需要保存str
相对于str_cp
的偏移量,并且在重新分配之后,让str
指向旧块的旧偏移量。
并且*str = (char *) c;
是错误的,尽管它在功能上等同于正确的*str = c;
的可能性非常小。
答案 1 :(得分:2)
*str = (char *) c;
这条线错了。
str
是指向char
的指针,*str
是char
,但您指定的char
指针指向char
。这不能在C中完成。
此外:
scanf("%d\n", &numStr);
\n
来电中的scanf
可能不符合您的预期:
http://c-faq.com/stdio/scanfhang.html
还有:
str = str_cp;
free(str_cp);
free(str);
你这里有两倍免费。在作业str
和str_cp
具有相同的值之后:
free(str_cp);
free(str);
就像你这样做:
free(str);
free(str);
这是未定义的行为(你不能免费两次)。