c - When I malloc more space for a string within an array of strings, the array of strings duplicates some strings -
i have array of strings, , trying malloc more space 1 of strings can change value of string.
int catenate_strings (char** arr, int index1, int index2) { char *new_string; new_string = malloc(1000*sizeof(char)); if (new_string == null) { printf("\nerror allocating memory\n"); } strcpy(new_string, arr[index1]); strcat(new_string, arr[index2]); arr[index1] = new_string; }
however when run code, work instances, in others duplicate string @ index1 , put @ index1 + 1 well.
your code has problems:
- memory leak in
arr[index1] = new_string
because not freeing old buffer. - buffer overflow if result string longer 1000 bytes.
- not returning value catenate_strings despite function having return value int.
if entries in arr
allocated using malloc
can use realloc
.
int catenate_strings (char** arr, int index1, int index2) { // resize buffer hold old string + new string (+ terminating null byte!) char * const new_string = realloc(strlen(arr[index1]) + strlen(arr[index2]) + 1); if (new_string == null) { printf("\nerror allocating memory, cannot resize string\n"); return -1; } strcat(new_string, arr[index2]); arr[index1] = new_string; return 0; }
the duplication index+1
comes not shown code somewhere else in code.
Comments
Post a Comment