C语言 getline()内存重新分配失败



使用FILE * some_file("somefile.txt", "r")成功打开文件后,我使用getline()读取一行。我可以提供getline()足够的缓冲char * line = malloc((size_t) 1024);,这样就可以了。我还可以提供比需要的更少的缓冲区-char * line = malloc((sizeof(char)))NULL-指针char * line = NULL;,并且,如预期的那样,getline()正在分配/重新分配和修改line的值。

char * line = malloc((sizeof(char)))
size_t n;
n = getline(&line, &n, some_file);

但是如果我声明一个指针而没有定义一些值或缓冲区,我得到错误not enough space(系统没有崩溃!).

char * line ;
size_t n;
n = getline(&line, &n, some_file); // Error: Not enough space

提供一个特定的缓冲区char * line = malloc(sizeof(char)))-这应该是一个指向char的指针(我知道我被允许使用这个内存由于malloc())和char * line;-这也应该是一个指向char的指针(当然我不知道我是否被允许使用这个内存,但程序没有崩溃)之间的区别在哪里?

问题是缺少变量初始化,这导致getline不期望的值。如果初始化,具有自动存储持续时间的变量具有不确定的值。使用这些值将导致未定义行为

初始化line的正确方法是设置为NULL并让getline做malloc它似乎合适,

如果你已经分配了一些内存,你坚持要在这里再次重用,那么n需要设置为大小内存分配的。即:

char * line = malloc(1);
size_t n = 1;
ssize_t rv = getline(&line, &n, some_file);

char * line = NULL
size_t n; // or can explicitly initialize this to `= 0` but it shouldn't matter
ssize_t rv = getline(&line, &n, some_file);

因此,你的问题中的节选是完全错误的.

最后,返回值类型为ssize_t,它与n无关。除了返回的值将严格小于大于n中存储的值。您不能将它存储在同一个变量中!


要用getline处理每一行,不需要调用malloc-只让getline处理内存分配:

char * line = NULL;
size_t n = 0;
while (1) {
errno = 0;
ssize_t rv = getline(&line, &n, some_file);
if (rv < 0) {
if (feof(some_file)) {
fprintf(stderr, "end of file, no problemo.");
}
else if (ferror(some_file)) {
perror("an error occurred while reading from the file");
}
else {
perror("some other error occurred");
}
free(line);
break;
}
// at this point `line` points to an array
// of `rv` characters, with possible embedded nulls,
// meaning one line of data from the file,
// + the terminating null character
//
// `n` is the *total number* of allocated bytes in the 
// allocation pointed to by `line`.
printf("I got a line of input: ");
fwrite(line, 1, rv, stdout);
}

最新更新