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:

  1. memory leak in arr[index1] = new_string because not freeing old buffer.
  2. buffer overflow if result string longer 1000 bytes.
  3. 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

Popular posts from this blog

android - Why am I getting the message 'Youractivity.java is not an activity subclass or alias' -

python - How do I create a list index that loops through integers in another list -

c# - “System.Security.Cryptography.CryptographicException: Keyset does not exist” when reading private key from remote machine -