我做了一个扫描功能,它实际上只是将文件中的行扫描成一个称为char *
的单个buffer
。但是,在读取几百行之后,该程序将停止运行。我刚得到一个程序已停止工作的弹出窗口。假设我在内存分配上做错了什么,但是我不确定是什么。
#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;
}
答案 0 :(得分:0)
代码无法使用返回值格式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;
}
答案 1 :(得分:0)
realloc()
的返回值realloc(NULL, size)
的工作方式与malloc(size)
相同;无需预先分配strlen()
#include <stdio.h>
#include <stdlib.h>
char *scanfile (FILE *fp)
{
size_t size, used;
char *buff = NULL;
int ch;
for (size=used=0;; ) {
ch = getc(fp);
if (ch == EOF) break;
if (used+1 >= size) {
size_t newsize = used? 2*used: 1024 ;
char *tmp = realloc(buff, newsize);
if (!tmp) FAIL();
else {buff = tmp; size = newsize; }
}
buff[used++] = ch;
}
/* Nothing read: return NULL */
if (!used) return NULL;
buff[used++] = 0;
/* maybe realloc (shrink) buff here */
return buff;
}