我想通过循环从文本文件中读取多行,但我的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);
我试过但未能修复它。任何解决方案将不胜感激。
答案 0 :(得分:1)
您需要执行以下任一操作。
将char *string = NULL;
和len
设置为0
。 [[Preferred method]]
将内存分配给char *string
并使用len
发送已分配内存的大小。
来自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.