strcat in c program is not working

user3815049 picture user3815049 · Aug 26, 2014 · Viewed 8.7k times · Source
#include<string.h>
#include<stdio.h>
void main()
{
    char *str1="hello";
    char *str2="world";
    strcat(str2,str1);
    printf("%s",str2);
}

If I run this program, I'm getting run time program termination.

Please help me.

If I use this:

char str1[]="hello";
char str2[]="world";

then it is working!

But why

char *str1="hello";
char *str2="world";

this code is not working????

Answer

gnasher729 picture gnasher729 · Aug 26, 2014

You are learning from a bad book. The main function should be declared as

int main (void);

Declaring it as void invokes undefined behaviour when the application finishes. Well, it doesn't finish yet, but eventually it will.

Get a book about the C language. You would find that

char *srt1="hello";

is compiled as if you wrote

static const char secret_array [6] = { 'h', 'e', 'l', 'l', 'o', 0 };
char* srt1 = (char*) &secret_array [0];

while

char srt1[]="hello";

is compiled as if you wrote

char srt1 [6] = { 'h', 'e', 'l', 'l', 'o', 0 };

Both strcat calls are severe bugs, because the destination of the strcat call doesn't have enough memory to contain the result. The first call is also a bug because you try to modify constant memory. In the first case, the bug leads to a crash, which is a good thing and lucky for you. In the second case the bug isn't immediately detected. Which is bad luck. You can bet that if you use code like this in a program that is shipped to a customer, it will crash if you are lucky, and lead to incorrect results that will cost your customer lots of money and get you sued otherwise.