簡體   English   中英

C malloc結構執行錯誤

[英]C malloc of struct execution error

我不明白為什么可以將malloc與struct var ** tableauVariables一起使用 ,但是我發現struct zone ** tableauZonesMemoireLibres出現錯誤。

調試時我會收到:

在C:\\ Users \\ Onel \\ Desktop \\ test \\ test.c:33程序收到信號SIGSEGV,分段錯誤。

我的代碼:

#include <stdlib.h>

void tabInit(), tabDelete();

struct zone {
    int pos;
    int taille;
};

struct var {
    char id[10];
    struct zone  tableau;
};

struct var **tableauVariables;
struct zone **tableauZonesMemoireLibres;
int tailleMemoire= 10;

int main () {

    tabInit();

    tabDelete();

    return 0;
}

void tabInit() {
    tableauVariables = (struct var**) malloc(sizeof(struct var) * tailleMemoire);
    tableauVariables[0] = NULL;

    tableauZonesMemoireLibres = (struct zone**) malloc(sizeof(struct zone) * tailleMemoire);
    tableauZonesMemoireLibres[0]->pos = 0; //Line 33 segmentation fault
    tableauZonesMemoireLibres[0]->taille = tailleMemoire;
    tableauZonesMemoireLibres[1] = NULL;

    return;
}

void tabDelete() {
    int i;

    for(i=0; tableauZonesMemoireLibres[i] != NULL; i++)
        free(tableauZonesMemoireLibres[i]);
    free(tableauZonesMemoireLibres);

    for(i=0; tableauVariables[i] != NULL; i++)
        free(tableauVariables[i]);
    free(tableauVariables);
}

您分配一個數組,並將其轉換為**。

這將分配一個大小為tailleMemoire的結構區數組。

tableauZonesMemoireLibres = (struct zone**) malloc(sizeof(struct zone) * tailleMemoire);

也許你的意圖是

struct zone *tableauZonesMemoireLibres;
tableauZonesMemoireLibres = malloc(sizeof(struct zone) * tailleMemoire);
tableauZonesMemoireLibres[0].pos = 0; //Line 33 segmentation fault
tableauZonesMemoireLibres[0].taille = tailleMemoire;

另外,您的tabDelete是完全錯誤的。 您需要一個免費的foreach malloc:

void tabDelete() {
    free(tableauZonesMemoireLibres);
    free(tableauVariables);
}

另一方面,如果您確實確實想要一個指針數組,那么該數組的每個元素都需要自己進行malloc。

暫無
暫無

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

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