Valgrind-getline()函数未初始化的值错误

时间:2014-11-27 07:33:00

标签: c valgrind getline

我想通过循环从文本文件中读取多行,但我的Conditional jump or move depends on uninitialised value(s)行中始终出现getline()错误。

我的代码:

char *string;
size_t len = 0;   

while (getline(&string, &len, fileStream) != -1) { // error happens this line   
    // do something  
}

free(string);   
fclose(fileSream);   

我试过但未能修复它。任何解决方案将不胜感激。

1 个答案:

答案 0 :(得分:1)

您需要执行以下任一操作。

  1. char *string = NULL;len设置为0 [[Preferred method]]

  2. 将内存分配给char *string并使用len发送已分配内存的大小。

  3. 来自man page的相关引用以供参考

       If *lineptr is set to NULL and *n is set 0 before the call, then
       getline() will allocate a buffer for storing the line.  This buffer
       should be freed by the user program even if getline() failed.
    
       Alternatively, before calling getline(), *lineptr can contain a
       pointer to a malloc(3)-allocated buffer *n bytes in size.  If the
       buffer is not large enough to hold the line, getline() resizes it
       with realloc(3), updating *lineptr and *n as necessary.