C中的简单字符串运行时错误?

Amo*_*wal 3 c memory-management cstring

这段代码编译得很好,但在运行时会出现分段错误错误?有谁能说出原因?

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

int main() {
    const char s2[] = "asdfasdf";
    char* s1;

    strcpy(s1, s2);
    printf("%s", s1);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

And*_*ton 13

就单一分配空间的指针,s1而不是字节指向的s1.

解决方案是为以下内容动态分配内存s1:

s1 = (char *)malloc(strlen(s2) + 1);
strcpy(s1, s2);
Run Code Online (Sandbox Code Playgroud)

请记住,您需要再分配一个字节的内存(调用中的+1 malloc)而不是字符数,s2因为最后有一个隐式NULL字节.

有关更多信息,请参阅C内存管理(堆栈溢出).