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

标签 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;
}

最佳答案

您为单个指针 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/

相关文章:

c++ - 如何编译c++而不包括cstdio和其他c标准库

c - 可见的副作用顺序

c - C 和 dlc 编译器出现奇怪的解析错误

键删除后 ruby​​ 哈希内存泄漏

c - 当我们重新给 char 指针赋值时,内存会发生什么?

c - 在函数调用中初始化 cstring 数组

c++ - CString 到 char*

c++ - 在 C 中返回堆栈数据;它是否正确取消分配?

c# - 一条new语句如何分配堆内存?

c++ - 链接错误 CString