我创建了一个扫描函数,它本质上只是将文件的行扫描到一个名为 buffer
的 char *
中。然而,在读取了几百行之后,程序就停止工作了。我刚刚收到一个程序已停止工作的弹出窗口。假设我在内存分配上做错了什么,但我不确定是什么。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *scan_file(FILE *fp);
#define MAX_LINE 200
int main(void) {
FILE *fp = fopen("test.txt", "r");
char *contents = scan_file(fp);
printf("%s\n", contents);
return 0;
}
// Scan in file into a buffer. Returns a malloc-ed string
char *scan_file(FILE *fp) {
int buf_len = 1;
int contents_len = buf_len;
char *buffer = malloc(sizeof(char) * (MAX_LINE + 1));
char *contents = malloc(sizeof(char) * (buf_len + 1));
strcpy(contents, "\0");
while (fgets(buffer, MAX_LINE, fp) != NULL) {
buf_len = strlen(buffer);
contents_len += buf_len;
realloc(contents ,contents_len);
strcat(contents, buffer);
strcpy(buffer, "\0");
}
free(buffer);
return contents;
}
最佳答案
代码无法使用返回值形式realloc()
分配大小减少 1。
重复 strcat()
会导致缓慢的 (n*n) 解决方案。
考虑使用 size_t
来确定数组大小,而不是使用 int
。
不要调用变量...len
,而是考虑...size
来确认最后一个空字符的存在字符串。
char *scan_file(FILE *fp) {
// int buf_len = 1;
size_t buf_size = 1;
// int contents_len = buf_len;
size_t contents_size = buf_size;
// char *buffer = malloc(sizeof(char) * (MAX_LINE + 1));
// fgets(..., MAX_LINE, ...) will only read up to MAX_LINE - 1 characters.
char *buffer = malloc(MAX_LINE);
char *contents = malloc(buf_size + 1u);
if (buffer == NULL || contents == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
// strcpy(contents, "\0");
contents[0] = '\0';
while (fgets(buffer, MAX_LINE, fp) != NULL) {
// buf_len = strlen(buffer);
buf_size = strlen(buffer) + 1u;
// contents_len += buf_len;
// realloc(contents ,contents_len);
void *p = realloc(contents ,contents_size + buf_size);
if (p == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
contents = p;
// strcat(contents, buffer);
strcpy(contents + contents_size, buffer);
// now add
contents_size += buf_size;
// Code here not truly needed, yet helps in debugging.
// strcpy(buffer, "\0");
buffer[0] = '\0';
}
free(buffer);
return contents;
}
关于c - 读取数百行后程序中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53310587/