我正在尝试动态分配一个结构数组,但每当我运行程序时,我都会得到: a.out(6487,0x7fff7ecb8300) malloc:* 对象 0x7fff6f670000 的错误:未分配正在重新分配的指针 *在malloc_error_break中设置断点进行调试
struct node {
char course[25];
char category[20];
char prereq[50];
char notes[50];
};
int main(int argc, char* argv[])
{
FILE *fp;
char *filename = argv[1];
char *token;
char buffer[100];
char *del = ",n";
int num = 5, i = 0, j =0, count = 0;
struct node *d = malloc(num * sizeof(struct node));
char** complete = malloc(num * sizeof(char*));
printf("%sn", filename);
if( (fp = fopen(filename, "r")) == NULL )
{
printf("unable to open %sn", filename);
exit(1);
}
while(fgets(buffer, sizeof(buffer), fp) != NULL)
{
if(count == num)
{
num = num + 5;
struct node *d = realloc(d, sizeof(d)*num);
printf("Reallocatingn");
}
token = strtok(buffer, del);
if(strncmp(token, "#", 1) != 0)
{
strcpy(d[count].course, token);
printf("%sn", d[count].course);
strcpy(d[count].category, strtok(NULL, del));
printf("%sn", d[count].category);
strcpy(d[count].prereq, strtok(NULL, del));
printf("%sn", d[count].prereq);
strcpy(d[count].notes, strtok(NULL, del));
printf("%sn", d[count].notes);
count++;
}
}
struct node *d = realloc(d, sizeof(d)*num);
您正在声明一个新的d
变量,该变量隐藏了前一个变量,并将其尚未初始化的值提供给realloc
。
您需要这样做:
struct node *newD = realloc(d, num * sizeof *d);
if(!newD) {
// Allocation failure, do something about it and break out
} /* else */
d = newD;
另请注意,我更正了sizeof
,它测量的是指针的大小,而不是脚尖的大小。
在:
struct node *d = realloc(d, sizeof(d)*num);
这将声明一个具有初始不确定值的新变量d
并将其传递给realloc
。将其更改为:
struct node *tmp = realloc(d, sizeof(*d)*num);
if(!tmp)
; // handle error
d = tmp;