从文件读取行导致崩溃

问题描述:

我试图从文件中逐字符读取一行,并将字符放在一个字符串中;这里'我的代码:从文件读取行导致崩溃

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行崩溃。如果我将该行移出循环或将其注释掉,它不会崩溃。如果我只是读取字符,然后将它们发送到标准输出,它一切正常(即文件打开正确)。问题在哪里?

您不能realloc首先与malloc生成的指针。

你也有一个错误的,会给你一些麻烦。

+0

而且我看到你已经修复了原始问题中的错误问题。很好。 –

你不能realloc一个字符串文字。而且,每个新字符都不是一个非常有效的方法。看看getline,一个GNU扩展。

你的代码更改为:

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'; 
} 

你的问题,因为你是一个指向内存的指针,这不是与任何mallocrealloc这是不允许的分配调用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. 

在一个侧面说明,你应该不会成长在一个时间缓冲一个字符,但保留两个反,一个用于缓冲能力,以及一个用于数字使用的字符,并且只在缓冲区满时增加。否则,你的算法会有很差的性能。

+0

在你的代码的最后一个语句中('str [len] ='\ 0';'),你正在为分配给'str'的​​内存写入界限。它看起来像@保罗有正确的指数。 –

+2

@DavidAlber,保罗对历史上没有出现的问题做了一个快速编辑。这里显示的指数来自原始数据,这就是为什么我在我的答案中提出了“一个一个”的评论。 –

+0

@DavidAlber谢谢你,我已经复制了包含这个错误的OP代码。我修复了它。 –