[英]Segmentation fault in my strcpy
由於以下事實,我正在編寫自己的strcpy
string.h
中的默認值僅接受const char *
作為要從中復制的源字符串。 我正在嘗試這個非常基本的原型(是的,回報沒有意義,我只是在嘗試事情):
int copyStrings(char * dest, char * source){
int i=0;
while(source[i]!='\0'){
dest[i]=source[i];
i++;
}
dest[i]='\0';
return 0;
}
它在第一個字符dest[i]=source[i]
行處給出了SIGSEGV, Segmentation Fault
gdb中的SIGSEGV, Segmentation Fault
錯誤。 我很確定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");
讓我們逐行查看它出了什么問題:
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;
}
int main(){
-這是main
的不正確定義。 應該是int main(int argc, char **argv)
char * str = (char*)malloc((int)sizeof(double));
-定義str
,然后(可能)分配8個字節的內存,並將其地址分配給str
。 malloc
使用size_t
參數,因此size_t
(int)sizeof(double)
不正確。 同樣,在C語言中, 絕對不要轉換 malloc
的返回值。 所以這行應該是char * str = malloc(sizeof(double));
char * str2 = (char *)malloc((int)sizeof(int));
-所有與上一行相同的問題。 應該是char *str2 = malloc(sizeof(int));
str = "hello";
-導致內存泄漏,因為您剛才在兩行分配的內存現在已無法挽回。 您在這里有兩個選擇-在定義str
時不分配內存或先釋放它。 讓我們做后者:
free(str);
str = "hello";
str2 = "hey jude";
-同樣的問題,類似的解決方案:
free(str2);
str2 = "hey jude";
copyStrings(str2, str);
-在這里,您要告訴您的例程將常量字符串“ hello”復制到常量字符串“ hey jude”的頂部。 這在某些系統上可以正常工作,但在其他系統上則會崩潰。 問題在於常量字符串“ hey jude”的處理。 如果將其存儲在可修改的內存中,則代碼可以正常工作。 但是,如果將其存儲在標記為不可修改的內存中,則會崩潰。 在您的系統上似乎是后者。 要解決此問題,您可能需要返回到上一行並將其更改為
str2 = malloc(20);
這比您所需的內存更多,但可以正常工作。
free(str);
-您試圖釋放常量字符串“ hello”,該常量不是動態分配的內存。 這需要在賦值str = "hello";
之前完成str = "hello";
。
free(str2;
-與上述相同的問題。這需要在賦值str2 = "hey jude";
。
}
-正確
祝你好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.