c - Size of allocated memory to a pointer changes when increment the pointer -
this question has answer here:
char *ptr = (char*)malloc(10); if(null == ptr) { printf("\n malloc failed \n"); return -1; } else if(argc == 1) { printf("\n usage \n"); } else { memset(ptr, 0, 10); strncpy(ptr, argv[1], 9); while(*ptr != 'z') { ptr++; } if(*ptr == 'z') { printf("\n string contains 'z'\n"); /* more processing */ } free(ptr); }
in previous code, lets arguments program is: mixx
, program gives segmentation error.
and question is:
when in while loop:
ptr++;
does mean size of memory allocated pointer ptr changes , that's why when call free() function crashes.
your hunch correct: behaviour of program undefined.
you must pass original value of ptr
free
.
(also, while(*ptr != 'z')
vulnerable overrunning input. consider checking \0
too.)
Comments
Post a Comment