c - 删除锯齿状数组时出现段错误

标签 c free

我尝试在创建锯齿状数组后释放它,但在尝试删除它时遇到了段错误问题:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {

    int *col;
    int **row;
    //Declare and fill col array 
    col = malloc(argc * sizeof (int));
    for (int k = 1; k < argc; k++) {
        col[k] = atoi(argv[k]);
    }
    row = malloc(argc * sizeof (int*));

    //build the ragged array
    for (int i = 0; i < argc; i++) {
        row[i] = malloc(sizeof (int) * col[i]);
        for (int j = 0; j < col[i]; j++) {
            row[i][j] = 1;
        }
    }

    //trying to delete it but its not working
    for (int i = 0; i < argc; i++) {
        for (int j = 0; j < col[i]; j++) {
            int* currentIntPtr = row[i];
            free(currentIntPtr);
        }
    }
    free(row);
    return 0;


}

编译器消息:

Segmentation fault (core dumped)

最佳答案

row = malloc(argc * sizeof (int));

这应该更改为:

row = malloc(argc * sizeof (int *));

当您为“row”中的每个元素分配一个新的整数数组时,“row”中的每个元素都必须是一个整数指针,以便它保存指向整数数组的地址。

此外,您以错误的方式释放内存。

for (int i = 0; i < argc; i++) {
    for (int j = 0; j < col[i]; j++) {
        int* currentIntPtr = row[i][j];
        free(currentIntPtr);
    }
}

这段代码不会工作:.

int* currentIntPtr = row[i][j];

row[i][j] 的类型是整数类型,并且您将其分配给整数指针。这样做的目的不是释放 row[i][j] ,而是使用 row[i][j] 的值尝试释放该地址,该地址可能超出程序的地址空间,因此是不允许的,因此段错误。

合适的工作方式是:

for (int i = 0; i < argc; i++) {
    int* currentIntPtr = row[i];
    free(currentIntPtr);
}

关于c - 删除锯齿状数组时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52349272/

相关文章:

c - 内核级内存处理编码

c - 在 C 中释放特定类型的内存分配

c - 信号 SIGTRAP 免费崩溃

c - 我需要释放固定长度的字符数组吗?

c - 打印c中的字符

c - C中的汇编代码

c++ - 免费(): invalid next size (fast) in Cpp

c++ - 双自由错误

c - 为什么 scanf ("%c", &ch ) 不从控制台读取字符,而 scanf ("%c", &ch ) 会

c - 如何在来自 AVS 的 http2 连接上接收超过 65535 字节的数据?