簡體   English   中英

具有realloc的動態2D陣列會產生分段錯誤,但可與malloc一起使用

[英]Dynamic 2D Array with realloc gives segmentation fault, but works with malloc

我的2D動態數組有問題。 使用malloc可以正常工作。 使用realloc ,它失敗了。

這行不通:

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

int main(int argc, char *const *argv) {

    unsigned ** gmatrix = NULL;
    int cap = 4;

    /*
    ...
    */

    gmatrix = realloc(gmatrix, 4 * sizeof(unsigned*));
    for(unsigned i = 0; i < cap; i++) {
        gmatrix[i] = realloc(gmatrix, cap* sizeof(unsigned));
    }
    // initialize:
    for(unsigned i = 0; i < cap; i++) {
        for(unsigned j =  0; j < cap; j++) {
            gmatrix[i][j] = 0;
        }
    }

}

但這確實是:

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

int main(int argc, char *const *argv) {

    unsigned ** gmatrix = NULL;
    int cap = 4;

    /*
    ...
    */
    gmatrix = malloc(cap * sizeof(unsigned*));
    for(unsigned i = 0; i < cap; i++) {
        gmatrix[i] = malloc(cap* sizeof(unsigned));
    }
    for(unsigned i = 0; i < cap; i++) {
        for(unsigned j =  0; j < cap; j++) {
            gmatrix[i][j] = 0;
        }
    }

}

在第一個代碼部分中,我遇到了分段錯誤錯誤。 為什么?

gmatrix[i] = realloc(gmatrix, cap* sizeof(unsigned));

應該

gmatrix[i] = realloc(gmatrix[i], cap* sizeof(unsigned));

使用gmatrix代替gmatrix[i]將導致未定義行為 ,而您遇到的分段錯誤是未定義行為的副作用之一。


編輯

@MattMcNabb 指出,在第一個malloc之后,應將gmatrix[i]初始化為NULL 因此,在第一次調用realloc之后使用以下命令:

for(unsigned i = 0; i < cap; i++) {
    gmatrix[i] = NULL;
    gmatrix[i] = realloc(gmatrix[i], cap* sizeof(unsigned));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM