user2442489
user2442489

Reputation:

Runtime error while doing string concatenation

What is the problem with the below program?

main( ) 
{ 
 char *str1 = "United" ; 
 char *str2 = "Front" ; 
 char *str3 ; 
 str3 = strcat ( str1, str2 ) ; 
 printf ( "\n%s", str3 ) ; 
} 

I am not able to compile the above program and it always give me runtime error. I am trying to concatenate the two string. Is there any error in the above program?

Thanks.

Upvotes: 1

Views: 2782

Answers (3)

Ron
Ron

Reputation: 1783

When you declare char *str = "someText", basically, you initialize a pointer to a string constant which can't be changed, and is located somewhere in your computer's memory.

After that by using the function strcat() you are trying to change that string constant, which we said is constant - Such behavior compiles with no errors, but will cause your program to crash during runtime since const (constant) works during runtime and is not precompiled like #define.

A different solution for you might be,

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

int main(void) {

    char* str1 = "Hello,";
    char* str2 = " World";
    char str3[30];

    strcpy(str3, str1);
    strcat(str3, str2);

    printf("%s\n", str3);
    printf("\n\n\n");
    return 0;
}

Hope that helps! Best of luck in the future!

Upvotes: 0

Aravind
Aravind

Reputation: 575

Make your char *str1 = "United" as

char str1[<required memory for concatenated resultant string>] = "United".

You need to allocate memory for the destination buffer which is str1. str3 will also receive address of str1 in the result. 'strcat' will not check for space availability in destination buffer (str1). Programmer has to take care of it.

Upvotes: 3

Jonathan Leffler
Jonathan Leffler

Reputation: 753990

You are trying to modify a string literal, but your compiler (and runtime support) won't let you. When you do so, you are invoking 'undefined behaviour', which is a Bad Thing!™ Anything could happen; it is legitimate for the program to crash. Avoid undefined behaviour.

You need to allocate enough (writable) memory for the strings, maybe like this:

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

int main(void)
{
    char *str1 = "United";
    char *str2 = "Front";
    char  str3[64];
    strcpy(str3, str1);
    strcat(str3, str2);
    printf("%s\n", str3);
    return(0);
}

Upvotes: 2

Related Questions