C语言 动态分配的二维矩阵上的分割错误



今天我尝试编写一些代码,但我只是无法弄清楚我做错了什么

问题是我怀疑,不知何故,我分配了这个矩阵,我得到了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 errorn");
        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, scanfn");
                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));

但我不确定。我到底做错了什么?

很高兴您正在使用 valgrind,但您没有正确理解输出。

==4842== 大小为 8 的读取无效

==4842== 在0x400886:主(程序.c:43)

==4842== 分配大小为 16 的块后的地址0x51fc050为 0 字节

==4842== 在0x4C2AB80: malloc (在/usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)

==4842== 按0x40071F: 主 (程序.c:11)

错误在第 43 行,即以下行:

if ( *(table + i) != NULL ) {

它正在读取您在第 11 行分配的内存之外的地址。这并不一定意味着第 11 行有什么问题。

问题是您迭代了行数而不是第 42 行中的列数:

for (int i = 0 ; i < COL ; i++){

这应该是:

for (int i = 0 ; i < ROW ; i++){

相关内容

  • 没有找到相关文章

最新更新