我正在尝试逐字符地从文件中读取一行,并将字符放在一个字符串中;这是'我的代码:
char *str = "";
size_t len = 1; /* I also count the terminating character */
char temp;
while ((temp = getc(file)) != EOF)
{
str = realloc(str, ++len * sizeof(char));
str[len-2] = temp;
str[len-1] = '\0';
}
程序在realloc
行崩溃。如果我将该行移到循环之外或将其注释掉,它就不会崩溃。如果我只是读取字符然后将它们发送到stdout,它一切正常(即文件正确打开)。问题出在哪里?
答案 0 :(得分:6)
您不能realloc
首先未使用malloc
生成的指针。
你还有一个一个一个错误,会给你一些麻烦。
答案 1 :(得分:6)
将您的代码更改为:
char *str = NULL; // realloc can be called with NULL
size_t len = 1; /* I also count the terminating character */
char temp;
while ((temp = getc(file)) != EOF)
{
str = (char *)realloc(str, ++len * sizeof(char));
str[len-2] = temp;
str[len-1] = '\0';
}
您的问题是因为您使用指向未分配realloc
或malloc
的内存的指针调用realloc
,这是不允许的。
来自realloc
联机帮助页:
realloc() changes the size of the memory block pointed to by ptr to size bytes.
The contents will be unchanged to the minimum of the old and new
sizes; newly allocated memory will be uninitialized. If ptr is NULL,
then the call is equivalent to malloc(size), for all values of size;
if size is equal to zero, and ptr is not NULL, then the call is
equivalent to free(ptr). Unless ptr is NULL, it must have been
returned by an earlier call to malloc(), calloc() or realloc(). If
the area pointed to was moved, a free(ptr) is done.
另一方面,你不应该一次增加缓冲区一个字符,但保留两个计数器,一个用于缓冲区容量,一个用于使用的字符数,只在缓冲区满时增加缓冲区。否则,您的算法的性能会非常差。
答案 2 :(得分:2)
你不能realloc
字符串文字。此外,realloc
每个新char都不是一种非常有效的方法。查看getline
,一个gnu扩展名。