Home > Blockchain >  Using strcat() on two string allocated with malloc() and then assigned using = causes segfault in C
Using strcat() on two string allocated with malloc() and then assigned using = causes segfault in C

Time:09-16

Trying to concat two strings that have been allocated using malloc doesn't seem to work, but if the variables are changed to John[4] and Carter[6] then it works?

Are there any alternatives besides changing the variables to "arrays"?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) {
  char* John = malloc(4);
  char* Carter = malloc(7);

  John = "John";
  Carter = "Carter";

  strcat(John, Carter);
  printf("%s\n", John);

  return 0;
}

CodePudding user response:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
    char* John = malloc(11); // This should hold enough space: 10   1 for '\0'
    char* Carter = malloc(7);
    
    strcpy(John, "John");
    strcpy(Carter, "Carter");
    
    strcat(John, Carter);
    printf("%s\n", John);
    
    // Release memory when done
    free(John);
    free(Carter);
}

Output:

JohnCarter

CodePudding user response:

What does a string literal mean?

“John” tells the compiler the store the for letters and a zero byte somewhere, preferably in read-only memory, and give you a pointer to that memory. So what have you done:

  1. You allocated a pointer to 4 bytes. Not enough for the string “John”, it needs five bytes. You stored the pointer in the variable John.
  2. You stored five bytes “John” in read-only memory, took a pointer to that memory, and stored that pointer in the variable John, overwriting the previous pointer.
  3. You called strcat, which tries to copy “Carter” to the end of “John” in read-only memory. Since it’s read-only memory, it crashes. If it didn’t crash, it would write 7 bytes somewhere into memory that is used for something different. That would be worse.

CodePudding user response:

For starters the program produces memory leaks because at first a memory was dynamically allocated

char* John = malloc(4);
char* Carter = malloc(7);

and its addresses were assigned to pointers John and Carter and then these pointers were reassigned with addresses of first characters of string literals.

John = "John";
Carter = "Carter";

So the addresses of the allocated memory are lost.

Moreover the pointer John shall point to a memory large enough to store the concatenated result string.

The program can look the following way

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) 
{
    char *John = malloc(12);
    strcpy( John, "John " );

    const char *Carter = "Carter";

    strcat( John, Carter );
    
    printf("%s\n", John);

    free( John );
    
    return 0;
}

Its output is

John Carter
  • Related