Runtime error while doing string concatenation

女生的网名这么多〃 提交于 2019-12-02 04:34:56

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.

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);
}

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!