【问题标题】:C malloc of struct execution errorstruct执行错误的C malloc
【发布时间】:2013-11-24 23:28:06
【问题描述】:

我不明白为什么我可以将 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);
}

【问题讨论】:

  • tableauVariables = malloc(sizeof(struct var *) * tailleMemoire); 或更简单、更健壮:tableauVariables = malloc(tailleMemoire * sizeof *tableauVariables );
  • 学习将 valgrind 用于此类事情。
  • 在接触调试器之前学习语言。调试器不会教你什么。顺便说一句:tableauZonesMemoireLibres:类似的错误。

标签: c struct segmentation-fault malloc free


【解决方案1】:

您分配一个数组,并将其转换为 **。

这分配了一个大小为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。谢谢
猜你喜欢
  • 2017-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-13
  • 1970-01-01
  • 2012-12-22
  • 2019-11-23
相关资源
最近更新 更多