Using strcat results in an empty string

I'm learning C and tried to make a little program to know how strings work. Using the strcat function with pointers to a char produces an empty string, even thought I initialize the first pointer dynamically with malloc. Why is this happening if both strings have been initialized?

Here's the code:

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

int main(void) 
{ 
    char *dest = (char*) malloc(sizeof(char) * 20);
    char *src = "World";

    dest = "Hello";

    printf("%s", strcat(dest, src)); // <-- gives an empty string
}

Upvotes: 1

Views: 495

Answers (1)

D&#250;thomhas
D&#250;thomhas

Reputation: 10028

You have changed what area of memory dest points to. (Remember, dest is a pointer, not an array or the memory itself.)

As a consequence you are now trying to write to read-only memory (where the "Hello" string is located in memory), which is causing failure.

An additional consequence is that the chunk of memory obtained by malloc was lost, as you now have no way to release it back to the memory manager. In software we call this a “leak”, as in it leaks memory.

To fix it, use strcpy to copy the "Hello" string to your allocated memory spot, which is both writable and, as you coded it, large enough to hold a 19-character string.

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

int main() 
{ 
   char *dest = (char *)malloc(sizeof(char) * 20);
   char *src = "World";

   // copy hello to dest[], replacing what was there before
   strcpy(dest, "Hello");  

   // append src[] to dest[], return dest, print it
   printf("%s", strcat(dest, src)); 

   // don't forget to clean up!
   free(dest);
}

Always remember to watch the size of your string arrays that they are large enough to accept everything you wish to append (concatenate) to them. In this example it is sufficient, but still very, very small.

You may also consider appending a space to separate your strings, and either printing a newline at the end of your input or flushing the output stream in order to guarantee immediate output.

Upvotes: 2

Related Questions