为什么我在函数中收到分段错误消息?

Why did I get a segmentation fault message in a function?

我在第 2 部分中使用基本上是关于内存和字符串的语言。我想在 C 中创建一个类似于 strcat() 的函数,所以这是我目前所拥有的:

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

char *add_str(char *str, char *str2);

int main() {
    char name[] = "MatthewGamer"; char name2[] = "PlayGames";
    printf("%s\n", add_str(name, name2));
}

char *add_str(char str[], char str2[]) {
    return strcat(str, str2);
}

并不是我想更改函数内部的内容,而是字符串连接后的问题。当我运行这个程序时,出现的是:

~/BPML/C/Phase2/ $ make add_str
clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow    add_str.c  -lcrypt -lcs50 -lm -o add_str
~/BPML/C/Phase2/ $ ./add_str
MatthewGamerPlayGames
Segmentation fault
~/BPML/C/Phase2/ $ 

是的,分段错误是紧接着出现的。我不明白它背后的机制,尽管我之前已经遇到过其中一种情况。

问:如果字符串中的代码有问题,我该如何解决?如果不是字符串,那是什么?

因为您的目标字符串太短并且 strcat 超出了数组边界。两个字符串都需要 space。

int main(void) {
    char name[sizeof("MatthewGamer") + sizeof("PlayGames") - 1] = "MatthewGamer"; char name2[] = "PlayGames";
    printf("%s\n", add_str(name, name2));
}

strcat 要求目标数组有一个已经以 null 结尾的字符串 并且 有额外的 space 来保存整个连接的字符串 and 空终止符,否则 行为 将是 undefined.

最扩展的解决方案是使用 strlenmallocmemcpy 而不是完全使用 strcat

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


char *concatenate(const char *s1, const char *s2) {
    size_t s1_len = strlen(s1);
    size_t s2_len = strlen(s2);
    char *ret = malloc(s1_len + s2_len + 1);
    memcpy(ret, s1, s1_len);

    // copy the null terminator too
    memcpy(ret + s1_len, s2, s2_len + 1);
    return ret;
}

int main(void) {
    char *concatenated = concatenate("Hello ", "World!");
    printf("%s\n", concatenate);
    free(concatenated);
}