[英]C "Process finished with exit code 133 (interrupted by signal 5: SIGTRAP)" when converting int to string
我目前正在失去希望,因為我找不到我的錯誤。 我在我的代碼中改變了很多,現在它很糟糕......從頭開始,我有一個鏈表:
struct list {
int value;
struct list *next;
};
為此,我實現了一個 function,它將每個現有值(因此每個“下一個”列表的值)轉換為“[value1,value2,...]”形式的串聯字符串。 這是 function:
char* cdl_to_string(list_t *list){
int tester = 1;
char* toString = malloc(2 * sizeof(char));
strcat(toString, "[");
if(list != NULL){
while ( tester !=0){
char *result = malloc(strlen(toString) * sizeof(char ) +1);
sprintf(result, "%d", list->value);
strcat(toString,result);
if(list->next != NULL){
strcat(toString, ", ");
}
else{
tester = 0;
}
list = list->next;
free(result);
}
}
strcat(toString, "]");
printf("%s",toString);
return toString;
free(toString);
}
我用這個斷言調用 function:
void givenListWithMultipleElements_toStringIsOk() {
list_t* head = create_node(INT_MIN);
list_t* second = create_node(INT_MAX);
list_t* third = create_node(0);
head->next = second;
second->next = third;
char* result = cdl_to_string(head);
assert(strcmp("[-2147483648, 2147483647, 0]", result) == 0);
TEST_SUCCESS("givenListWithMultipleElements_toStringIsOk");
free(third);
free(second);
free(head);
}
奇怪的是,當我在控制台或 IDE 中使用 Clang 編譯它時,它因標題錯誤而失敗,但在 Intellij 調試器中它每隔一段時間就可以工作?
我很感激每一個建議!
編輯:這里是控制台編譯器中的完整錯誤:
[ OK ] whenInitList_thenListIsCreated
[ OK ] givenEmptyList_thenReturnSizeOfZero
[ OK ] givenListWithOneElement_thenReturnSizeOfOne
[][ OK ] givenEmptyList_toStringIsOk
zsh: trace trap ./a.out
在 intellij 中:
[ OK ] whenInitList_thenListIsCreated
[ OK ] givenEmptyList_thenReturnSizeOfZero
[ OK ] givenListWithOneElement_thenReturnSizeOfOne
[][ OK ] givenEmptyList_toStringIsOk
Process finished with exit code 133 (interrupted by signal 5: SIGTRAP)
“不要失去希望,也不要悲傷。”
該聲明:
char* toString = malloc(2 * sizeof(char));
為 2 個字節分配 memory,包括空終止符。
然后,調用strcat()
:
strcat(toString, "[");
嘗試將字符串連接到未初始化的 memory。如果我們查看手冊頁:
strcat() function 將 src 字符串附加到 dest 字符串,覆蓋 dest 末尾的終止 null 字節('\0'),然后添加終止 null 字節。 字符串不能重疊,並且目標字符串必須有足夠的空間用於結果。 如果 dest 不夠大,程序行為是不可預測的; 緩沖區溢出是攻擊安全程序最喜歡的途徑
我們看到strcat()
必須首先使用從字符串開頭開始的搜索找到終止字符串的 null 字節,但您從未初始化toString
的內容,因此這會調用未定義的行為。
那么對strlen()
的調用不太可能成功:
char *result = malloc(strlen(toString) * sizeof(char ) +1);
如果toString
正確地以 null 終止,這也只會為result
分配 2 個字節,這可能不能(而且看起來肯定不能)能夠表示list->value
的值。
對strcat()
的后續調用具有相同的問題。
旁白:不要丟棄mallloc()
的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.