【发布时间】:2016-08-23 13:29:13
【问题描述】:
我在使用此代码时遇到了一些问题,希望得到一些帮助。该函数从文件中读取动态分配的内存
感谢@JonathanLeffler 的帮助 - 函数缩进效果很好!但是又出现了一个问题:使用函数 read_file,从文件读取到字符数组,然后传递给缩进。
================================================ ============================
//--------------- read_file valgrind validations --------------------
==396== 144 bytes in 1 blocks are definitely lost in loss record 62 of 66
==396== at 0x4C2AD10: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==396== by 0x401AC1: read_file (polisher.c:24)
==396== by 0x4025CE: test_indent (test_source.c:174)
==396== by 0x406BC7: srunner_run (in /tmc/test/test)
==396== by 0x402C67: tmc_run_tests (tmc-check.c:134)
==396== by 0x402902: main (test_source.c:235)
==396==
================================================ ======
char *read_file(const char *filename)
{
FILE *f = fopen(filename, "r");
if(!f)
return NULL;
int n = 0, c = 0;
char *a = NULL;
c = fgetc(f);
while(c != EOF)
{
n++;
c = fgetc(f);
}
freopen(filename, "r", f);
a = calloc(n + 1, sizeof(char));
c = fgetc(f);
n = 0;
while(c != EOF)
{
a[n] = c;
n++;
c = fgetc(f);
}
a[n] = '\0';
fclose(f);
return a;
}
================================================ =================
START_TEST(test_indent)
{
char *str = read_file("testifile.c");
if (!str) str = read_file("test/testifile.c");
if (!str) {
fail("[M6.01.c] read_file(\"testifile.c\") returned NULL");
}
char *res = indent(str, " ");
if (!res) {
free(str);
free(res);
fail("[M6.01.c] indent(\"testifile.c\") returned NULL");
}
char buf[OUTPUTLEN];
if (mycompare_new(res, ref61c, buf, OUTPUTLEN)) {
free(res);
free(str);
fail("[M6.01.c] Invalid string from indent(\"testifile.c\"): %s", buf);
}
free(str);
free(res);
test_complete();
}
END_TEST
【问题讨论】:
-
第一个问题的错误是什么?对于 valgrind 输出,你能指出哪一行出错(哪一行代码是第 116、127、...行)?
-
@Garf365
strncpy(dest + dest_offset, pad, pad_len + 1);是 116。dest[dest_offset++] = c;是 127。当我尝试将此函数发送到服务器时,它显示“提前退出,返回值 1”。第一个问题的错误信息是“Received signal: SIGABRT (Aborted). For main, PID 9424” -
请编辑您的问题以添加此信息。此外,检查每次在 valgrind 输出中提到函数
indent并为每个提到的行添加有关行的信息 -
@Garf365 好的,完成。
-
错误消息说“您分配了 144 个字节(例如
char *space = malloc(144);),然后您尝试写入不属于分配空间的space[144]。当然,这是不允许的。
标签: c linux optimization valgrind indentation