今天我尝试编写代码,但我无法弄清楚我做错了什么
我怀疑的是,我以某种方式分配了这个矩阵有些错误,我得到了Segmentation fault
,这意味着我试图访问一些不存在的内存位置。属于我。
以下是该计划:
#include<stdio.h>
#include<stdlib.h>
#define ROW 2
#define COL 5
int main(void){
int **table;
/* allocate memory for the pointers to rows */
table = malloc(ROW * sizeof(*table));
if(table){
/* dynamic number of elements */
for (int i = 0 ; i < ROW ; i++){
/* Memory allocation for the number of items in each ROW */
*(table + i) = malloc( COL * sizeof(*table[i]) );
}
}else{
printf("Malloc error\n");
exit(1);
}
printf("Type 10 Numbers: ");
for (int i = 0 ; i < ROW ; i++){
for (int j = 0 ; j < COL ; j++){
if((scanf("%d",&*(*(table+i)+j))) != 1){
printf("Error, scanf\n");
exit(2);
}
}
}
printf("The numbers are:\n");
for (int i = 0 ; i < ROW ; i++){
for (int j = 0 ; j < COL ; j++){
printf("%d ",*(*(table+i)+j));
}
printf("\n");
}
for (int i = 0 ; i < COL ; i++){
if ( *(table + i) != NULL ) {
free ( *(table + i) );
*(table + i) = NULL;
}
}
if(table){
free(table);
}
printf("\n");
}
以下是Valgrind
所说的内容:
==4842== Command: ./program
==4842==
Type 10 Numbers: 10 20 30 40 50 10 20 30 40 50
The numbers are:
10 20 30 40 50
10 20 30 40 50
==4842== Invalid read of size 8
==4842== at 0x400886: main (program.c:43)
==4842== Address 0x51fc050 is 0 bytes after a block of size 16 alloc'd
==4842== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4842== by 0x40071F: main (program.c:11)
==4842==
==4842==
==4842== HEAP SUMMARY:
==4842== in use at exit: 0 bytes in 0 blocks
==4842== total heap usage: 3 allocs, 3 frees, 56 bytes allocated
==4842==
==4842== All heap blocks were freed -- no leaks are possible
==4842==
==4842== For counts of detected and suppressed errors, rerun with: -v
==4842== ERROR SUMMARY: 3 errors from 1 contexts (suppressed: 0 from 0)
所以问题似乎在这里:
table = malloc(ROW * sizeof(*table));
但我不确定。究竟我在这里做错了什么?
答案 0 :(得分:3)
您使用valgrind很好,但您还没有正确理解输出。
== 4842 ==读取大小为8
== 4842 ==在0x400886:main(program.c:43)
== 4842 ==地址0x51fc050在大小为16的块之后是0字节&#39; d
== 4842 ==在0x4C2AB80:malloc(在/usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so中)
== 4842 == by 0x40071F:main(program.c:11)
错误在第43行,即此行:
if ( *(table + i) != NULL ) {
它正在读取您在第11行分配的内存之外的地址。这并不一定意味着第11行有任何问题。
问题是你已经迭代了行数而不是第42行中的列数:
for (int i = 0 ; i < COL ; i++){
这应该是:
for (int i = 0 ; i < ROW ; i++){