读取文件时 valgrind 出错 - C

Errors in valgrind when reading a file - C

所以,我无法弄清楚 valgrind 给我的错误是什么意思。

我的代码接收一个数独文件并检查它是否正确。它在命令行中接收文件名,打开它并执行它应该做的一切,检查它是否正确。

示例:

./run sudoku.txt

代码 运行ning 绝对没问题,但是当我 运行ned valgrind 时,它指出了两个我根本不理解的错误,但我认为它在文件处理中.

这是 valgrind 运行:

==20853== Syscall param openat(filename) points to unaddressable byte(s)
==20853==    at 0x4F4BD9E: open (open64.c:47)
==20853==    by 0x4EC85F9: _IO_file_open (fileops.c:189)
==20853==    by 0x4EC85F9: _IO_file_fopen@@GLIBC_2.2.5 (fileops.c:281)
==20853==    by 0x4EBAF19: __fopen_internal (iofopen.c:78)
==20853==    by 0x4EBAF19: fopen@@GLIBC_2.2.5 (iofopen.c:89)
==20853==    by 0x108BD1: main (q1_acs2.c:90)
==20853==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==20853== 
==20853== Invalid read of size 4
==20853==    at 0x4EB82BD: __isoc99_fscanf (isoc99_fscanf.c:30)
==20853==    by 0x108D4E: main (q1_acs2.c:96)
==20853==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==20853== 
==20853== 
==20853== Process terminating with default action of signal 11 (SIGSEGV)
==20853==  Access not within mapped region at address 0x0
==20853==    at 0x4EB82BD: __isoc99_fscanf (isoc99_fscanf.c:30)
==20853==    by 0x108D4E: main (q1_acs2.c:96)
==20853==  If you believe this happened as a result of a stack
==20853==  overflow in your program's main thread (unlikely but
==20853==  possible), you can try to increase the size of the
==20853==  main thread stack using the --main-stacksize= flag.
==20853==  The main thread stack size used in this run was 8388608.
==20853== 
==20853== HEAP SUMMARY:
==20853==     in use at exit: 0 bytes in 0 blocks
==20853==   total heap usage: 1 allocs, 1 frees, 552 bytes allocated
==20853== 
==20853== All heap blocks were freed -- no leaks are possible
==20853== 
==20853== For counts of detected and suppressed errors, rerun with: -v
==20853== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
Segmentation Fault

这是我打开文件并将其存储在矩阵中的代码部分: (我会把行号放在里面,这样你就可以看到它指向错误的地方)

85 int main(int argc, char *argv[])
86 {
87 int r = 9, c = 9, flag = 0;
88 FILE *px;
89
90 px = fopen(argv[1], "r");
91 int mat[r][c];
92
93 for (int i = 0; i < r; i++) {
94  for (int j = 0; j < c; j++)
95      if (j < 8)
96          fscanf(px, "%d,", &mat[i][j]);
97      else
98          fscanf(px, "%d", &mat[i][j]);
99 }
100 fclose(px);

尽管您在文本中提出了建议,但 Valgrind 的输出显示您尚未向程序传递参数。在将 argv[1] 传递给 fopen() 之前,您没有检查它是否有效。由于您省略了文件名参数,因此 argv[1] 是空指针,并且系统使用空指针向您提出对象。

==20853==  Address 0x0 is not stack'd, malloc'd or (recently) free'd

一个空指针……报告的错误都提到了'address 0x0`;您的代码没有进行适当的错误检查。

您也没有检查 fopen() 是否成功,如果给定的文件不可打开,这将导致麻烦。您也不检查对 fscanf() 的调用是否成功;如果文件的内容与您预期的不一样,那也会造成麻烦。

如果如您所说,您已将文件名传递给程序,您会在 Valgrind 输出的顶部看到它。您还没有显示该信息。

我想你错过了检查 fscanf 的 return 值;把它放在 if 语句中:

if (fscanf(fp, "%d", &value) == 1)

然后检查结果,不会扩展整数。