【发布时间】: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