一切似乎工作得很好,内存正在分配和释放并执行它应该做的事情但是当我用valgrind检查它时--track-originins =是我在输入一个名字和一个数字后得到这个条件跳转
==25590== Conditional jump or move depends on uninitialised value(s)
==25590== at 0x4007BD: add_car (in /students/5/gmi6y5/cs2050/lab4/a.out)
==25590== by 0x400704: main (in /students/5/gmi6y5/cs2050/lab4/a.out)
==25590== Uninitialised value was created by a heap allocation
==25590== at 0x4A069EE: malloc (vg_replace_malloc.c:270)
==25590== by 0x4006D9: main (in /students/5/gmi6y5/cs2050/lab4/a.out)
typedef struct FreightCars_
{
char *name;
int number;
struct FreightCars_ *next_car;
}FreightCar;
int main(int argc, char *argv[])
{
if(argc != 2)
{
printf("Insufficient number of arguements\n");
return 0;
}
int size = atoi(argv[1]);
FreightCar *engine = (FreightCar*)malloc(sizeof(FreightCar));
int i;
for(i=0;i<size;i++)
{
printf("Enter in freight car name and number: ");
add_car(engine);
}
free_cars(engine);
return 0;
}
void add_car(FreightCar *engine)
{
FreightCar *newPtr = (FreightCar*)malloc(sizeof(FreightCar));
newPtr->name = malloc(sizeof(char) * MAX_STR_LEN);
if(newPtr == NULL)
{
printf("Unable to allocate memory\n");
exit(1);
}
scanf("%s", newPtr->name);
scanf("%d", &newPtr->number);
newPtr->next_car = NULL;
if(engine->next_car == NULL)
{
engine->next_car = newPtr;
printf("added at the beginning\n");
}
else
{
FreightCar *currentPtr = engine;
while(currentPtr->next_car != NULL)
{
currentPtr = currentPtr->next_car;
}
currentPtr->next_car = newPtr;
printf("added later\n");
}
free(newPtr->name);
}
void free_cars(FreightCar *engine)
{
if(engine == NULL)
{
printf("Linked list is empty now\n");
}
else
{
free_cars(engine->next_car);
}
free(engine);
engine = NULL;
}
答案 0 :(得分:1)
主要是你做
FreightCar *engine = (FreightCar*)malloc(sizeof(FreightCar));
然后在for循环中调用
add_car(engine);
add_car确实
if(engine->next_car == NULL)
但正如@Oli Charlesworth在评论中指出的那样,你没有初始化引擎指向的内存,因此你在这里根据单位化内存内容作出决定,因此Valgrind投诉。