Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

c - unite two strings by copying one by one the characters of the second at the end of the first

this program it suppose to print Hello World but guess what exited, segmentation fault why is that happening ?

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

char f(char *a, char *b) 
{
    int i , m, n;
    m = strlen(a);
    n = strlen(b);
    for (i = 0; i<=n; i++)
    {
        a[m+i] = b[i];
    }
}

int main() {
char*str1 = "hello ";
char*str2 = "world!";
str1=f(str1, str2);
printf("%s", str1);
return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

You are not allowed to modify string literals. Use arrays with enough elements instead for strings to be modified.

Also assigning the return value of f to str1 is a bad idea because no return statement is executed in the function f and using its return value invokes undefined behavior. The return type should be changed to void if you are not going to return anything.

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

void f(char *a, char *b) 
{
    int i , m, n;
    m = strlen(a);
    n = strlen(b);
    for (i = 0; i<=n; i++)
    {
        a[m+i] = b[i];
    }
}

int main() {
    char str1[16] = "hello ";
    char*str2 = "world!";
    f(str1, str2);
    printf("%s", str1);
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...