简体   繁体   中英

Why is this usage of memset() segfaulting?

#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;
}

This code causes a segfault, any ideas why? I have already tried passing it as a memory address and as a pointer.

This is a string literal. It's immutable. Can't be changed.

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

You're trying to change it with memset. You could use an array of characters

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

or

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

You can't modify a string literal. It will invoke undefined behavior .
Try this instead

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM