c - Not sure where there is an unitialized value created by heap allocation -
c - Not sure where there is an unitialized value created by heap allocation -
everything seems working fine, memory allocating , freeing , doing supposed doing when check valgrind --track-origins=yes conditional jump after entering in name , number.
==25590== conditional jump or move depends on uninitialised value(s) ==25590== @ 0x4007bd: add_car (in /students/5/gmi6y5/cs2050/lab4/a.out) ==25590== 0x400704: main (in /students/5/gmi6y5/cs2050/lab4/a.out) ==25590== uninitialised value created heap allocation ==25590== @ 0x4a069ee: malloc (vg_replace_malloc.c:270) ==25590== 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"); homecoming 0; } int size = atoi(argv[1]); freightcar *engine = (freightcar*)malloc(sizeof(freightcar)); int i; for(i=0;i<size;i++) { printf("enter in freight auto name , number: "); add_car(engine); } free_cars(engine); homecoming 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 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 @ 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 empty now\n"); } else { free_cars(engine->next_car); } free(engine); engine = null; }
in main do
freightcar *engine = (freightcar*)malloc(sizeof(freightcar));
then in loop call
add_car(engine);
add_car does
if(engine->next_car == null)
but @oli charlesworth pointed out in comment, have not initialised memory pointed engine, making decision based on unitialised memory contents here, hence valgrind complaint.
c memory malloc
Comments
Post a Comment