-1

I have an array of strings, and I am trying to malloc more space for one of those strings so I can change the value of the 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 I run my code, it will work for some instances, but in others it will duplicate the string at index1 and put it at index1 + 1 as well.

Werner Henze
  • 16,404
  • 12
  • 44
  • 69

1 Answers1

1

Your code has some problems:

  1. Memory leak in arr[index1] = new_string because you are not freeing the old buffer.
  2. Buffer overflow if the result string is longer than 1000 bytes.
  3. Not returning any value from catenate_strings despite the function having return value int.

If all entries in arr are allocated using malloc then you can use realloc.

int catenate_strings (char** arr, int index1, int index2)
{ 
    // Resize buffer to 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 to index+1 comes not from the shown code but from somewhere else in your code.

Werner Henze
  • 16,404
  • 12
  • 44
  • 69