调用 strcpy 时出现分段错误

Segmentation fault when calling strcpy

我尝试使用 strncpy,然后使用 strcpy,反之亦然,但我在运行时一直收到分段错误。我以为这是因为函数中的逻辑错误,但我调换了它们的位置,只有第一个会执行。

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

int main(void)
{
    char c = ' ', sentence[50], *pointer_to_string;
    pointer_to_string = &sentence[0];
    int index = 0;

    printf("Please enter a sentence:");
    while ((c = getchar()) != '\n')
    {
        sentence[index] = c;
        index++;
    }
    sentence[index] = '[=10=]';

    char *string_copy1, *string_copy2;

    strncpy(string_copy1, pointer_to_string, 5);
    printf("strncpy(string_copy1, pointer_to_string, 5):\n");
    printf("%s\n", string_copy1);

    strcpy(string_copy2, pointer_to_string);
    printf("strcpy(string_copy2, pointer_to_string):\n");
    printf("%s\n", string_copy2);
}

documentation:

char *strcpy(char *dest, const char *src);

第一个参数是指向目标缓冲区的指针。但是你的指针没有初始化:

char *string_copy1, *string_copy2;

因此,指针包含一些垃圾值。而strcpy()写入不属于你程序的内存。它导致 segmentation fault.

char string_copy1[50] = { 0 };
char string_copy2[50] = { 0 };

用零填充它们是必要的,以避免 strncpy():

出现问题

If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated.