Search code examples
csegmentation-faultmemset

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.


Solution

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

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