此代码编译正常但在运行时出现段错误?谁能告诉我为什么?
#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;
}
最佳答案
您为单个指针 s1
分配了空间,但没有为s1
指向的字节分配空间。
一个解决方案是为s1
动态分配内存:
s1 = (char *)malloc(strlen(s2) + 1);
strcpy(s1, s2);
请记住,您需要分配比 s2
中的字符数多一个字节的内存(调用 malloc
时的 +1),因为有末尾的隐式 NULL
字节。
参见 C Memory Management (Stack Overflow)获取更多信息。
关于c - C 中的简单字符串运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1295114/