c - 我的 strcpy 中的段错误

标签 c string pointers char strcpy

我正在编写自己的 strcpy,因为 string.h 中的默认值仅接受 const char * 作为要从中复制的源字符串。 我正在尝试这个非常基本的原型(prototype)(是的,返回没有意义,我只是在尝试):

int copyStrings(char * dest, char * source){
    int i=0;
    while(source[i]!='\0'){
        dest[i]=source[i];
        i++;
    }
    dest[i]='\0';
    return 0;
}

它给我 SIGSEGV, Segmentation Fault gdb 错误,在 dest[i]=source[i] 行,就在 first 字符。我很确定 dest[i] 不是字符串文字,所以我应该能够修改它。

我做错了什么?

编辑:这是调用

int main(){
    char * str = (char*)malloc((int)sizeof(double));
    char * str2 = (char *)malloc((int)sizeof(int));
    str = "hello";
    str2 = "hey jude";
    copyStrings(str2, str);
    free(str);
    free(str2);
    return 0;
}

最佳答案

这是将字符串文字分配给 str2 - 这正是您声称自己没有做的事情。这实际上是您的段错误的原因。

str2 = "hey jude";

它也会导致内存泄漏,因为在此之前,您 malloc 分配了一些内存并将其分配给 str2。但是没有足够的内存来保存字符串。通常 int 是 4 个字节,您需要 9 个字节来存储该字符串。

你想要做的是这个,它分配与字符串中一样多的字节,再加上一个额外的字节来存储末尾的 \0 终止字符。

str2 = malloc(strlen("hey jude")+1);
strcpy(str2,"hey jude");

或者在某些系统上您可以使用 POSIX 函数 strdup()它通过一个方便的函数调用有效地完成了上述工作。

str2 = strdup("hey jude");

关于c - 我的 strcpy 中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51405043/

相关文章:

c++ - 在 Windbg 中转储值和填充

c - sizeof(int) <= sizeof(long) <= sizeof(long long) 总是正确的?

c++ - 如何在 GVim 中禁用高亮括号

c++ - 将字符串存储为 char[] 并放置新的并将其取回

C++ 函数指针赋值不能转换类内的类型

c - 参数在传递到函数时被破坏?

c - 如何使用指向 C 中结构指针的指针?

php - 从 SQL 查询打印数据

javascript regExp检查最后一个字符

c - 重新分配无效的下一个大小