为啥 memset() 的这种用法会出现段错误?

Posted

技术标签:

【中文标题】为啥 memset() 的这种用法会出现段错误?【英文标题】:Why is this usage of memset() segfaulting?为什么 memset() 的这种用法会出现段错误? 【发布时间】:2013-12-02 22:49:40 【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) 
    char *str = "This is a string!";
    int therealthing = sizeof(str[0]) * 4;
    memset(str, 'b', therealthing);
    printf("%s\n", str);
    return 0;

此代码导致段错误,有什么想法吗? 我已经尝试将它作为内存地址和指针传递。

【问题讨论】:

【参考方案1】:

这是一个字符串文字。它是不可变的。无法更改。

char *str = "This is a string!";

您正在尝试使用 memset 更改它。你可以使用一个字符数组

char str[] = "This is a string!";

char * str = malloc(sizeof(char) * (strlen("This is a string!") + 1));
strcpy(str, "This is a string!");

【讨论】:

【参考方案2】:

您不能修改字符串文字。它将调用未定义的行为。 试试这个吧

char str[] = "This is a string!";

【讨论】:

+ 他应该得到警告

以上是关于为啥 memset() 的这种用法会出现段错误?的主要内容,如果未能解决你的问题,请参考以下文章