我正在编写一个相当长的程序,其中包含大量数据导入,但我开始收到错误munmap_chunk(): invalid pointer。我环顾四周,这似乎是free()功能造成的。然后我在程序中注释了所有此类函数,但错误仍然发生。我所能发现的是,这可能是由内存问题引起的,我应该运行 Valgrind。所以我这样做了,它返回了一大堆错误,主要与我的导入函数有关。特别是这个:
void import_bn(int depth, int idx, float pdata[4][depth]) {
// [0][:] is gamma, [1][:] is beta, [2][:] is moving mean, [3][:] is moving variance
// Define name from index
char name[12]; // maximum number of characters is "paramxx.csv" = 11
sprintf(name, "param%d.csv", idx);
// open file
FILE *fptr;
fptr = fopen(name, "r");
if (fptr == NULL) {
perror("fopen()");
exit(EXIT_FAILURE);
}
char c = fgetc(fptr); // generic char
char s[13]; // string, maximum number of characters is "-xxx.xxxxxxx" = 12
char* a; // pointer for strtof
for (int t = 0; t < 4; ++t) { // type
for (int d = 0; d < depth; ++d) { // depth
//skip S
if (c == 'S') {c = fgetc(fptr);c = fgetc(fptr);}
// write string
for (int i=0; c != '\n'; ++i) {
s[i] = c;
c = fgetc(fptr);
}
float f = strtof(s,&a); // convert to float
pdata[t][d] = f; // save on array
c = fgetc(fptr);
}}
fclose(fptr);
}
Run Code Online (Sandbox Code Playgroud)
应打开的文件始终具有以下格式:
0.6121762
1.5259982
1.6705754
0.6907939
0.5508608
1.2173915
S
2.2555487
2.9224594
-1.6631562
-1.2156529
1.6944195
1.0379710
...etc
Run Code Online (Sandbox Code Playgroud)
所以基本上它们是由 '\n' 分隔的 float32,并且每个批次由“S”分隔。这表示一个多维数组,在此函数的情况下,总是有 4 个批次,但大小各不相同。
Valgrind 中经常出现的错误之一是Use of uninitialised value of size 8在线错误float f = strtof(s,&a);。难道是我用strtof()错了?
Valgrind 的完整结果可以在这里找到: https: //pastebin.com/rKwTUgut
第一个参数strtof()必须是一个以 null 结尾的字符串。您没有在// write string循环后添加空终止符。
int i;
for (i=0; c != '\n'; ++i) {
s[i] = c;
c = fgetc(fptr);
}
s[i] = '\0';
Run Code Online (Sandbox Code Playgroud)