[英]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;
}
這段代碼導致了段錯,任何想法為什么? 我已經嘗試將其作為內存地址和指針傳遞。
這是一個字符串文字。 這是不可改變的。 無法改變。
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!");
您無法修改字符串文字。 它將調用未定義的行為 。
試試這個
char str[] = "This is a string!";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.