我在下面的 fscanf 行上遇到分段错误。我为每个变量添加了字符宽度以尝试修复它,所以我不明白为什么它会出现段错误。
我从 CSV 文件中读取到结构数组。
结构是:
typedef struct Person
{
int ID;
int salary;
int deleted;
char salutation[4];
char firstName[21];
char surName[31];
char job[16];
} Person;
我声明了结构数组:
Person* persons;
persons = (Person*)malloc(SIZE * sizeof(Person));
然后使用这个 while 循环将 CSV 文件读入值:
(我初始化为0)
while(fscanf(f, "%d,%3[^,],%20[^,],%30[^,],%15[^,],%d,%d", &inPersons[i].ID, inPersons[i].salutation, inPersons[i].firstName, inPersons[i].surName, inPersons[i].job, &inPersons[i].salary, &inPersons[i].deleted)!=EOF)
{
newID = inPersons[i].ID;
i++;
}
段错误发生在 fscanf 语句期间。我没有使用 valgrind 的经验,但它给了我该行的这个错误:
==16810== Invalid write of size 4
==16810== at 0x578215: _IO_vfscanf (in /lib/libc-2.12.so)
==16810== by 0x585368: __isoc99_fscanf (in /lib/libc-2.12.so)
==16810== by 0x8048951: loadDb (Database.c:23)
==16810== by 0x8048711: menu (Menu.c:37)
==16810== by 0x804861E: main (main.c:6)
==16810== Address 0x27230128 is not stack'd, malloc'd or (recently) free'd
我也得到了同一行的这些 Valgrind 故障:
==18457== Use of uninitialised value of size 4
==18457== at 0x405A215: _IO_vfscanf (in /lib/libc-2.12.so)
==18457== by 0x4067368: __isoc99_fscanf (in /lib/libc-2.12.so)
==18457== by 0x8048943: loadDb (Database.c:23)
==18457== by 0x8048711: menu (Menu.c:37)
==18457== by 0x804861E: main (main.c:6)
==18457== Process terminating with default action of signal 11 (SIGSEGV)
==18457== Access not within mapped region at address 0x5C5E4128
==18457== at 0x405A215: _IO_vfscanf (in /lib/libc-2.12.so)
==18457== by 0x4067368: __isoc99_fscanf (in /lib/libc-2.12.so)
==18457== by 0x8048943: loadDb (Database.c:23)
==18457== by 0x8048711: menu (Menu.c:37)
==18457== by 0x804861E: main (main.c:6)