[英]Why does "malloc(): corrupted top size" error get fixed when I have printf() before/after it?
給定一個絕對路徑,我試圖獲取某個目錄之后的部分。 getTargetPath
函數就是這樣做的,當我編譯並運行下面的代碼時,代碼給了我預期的輸出。
問題是當我在printf("\\n")
malloc
行之前刪除printf("\\n")
,我得到:
malloc(): 損壞的頂部大小
中止(核心轉儲)
因此,當我在malloc
行之前或之后放置printf("\\n")
,代碼似乎工作正常,但是當我刪除它時,出現上述錯誤。
我的問題是,為什么會發生這種情況? 我不是要求解決我的路徑字符串問題。 我只想了解是什么導致了這種行為。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char* getTargetPath(const char* source)
{
int count = 0;
int i = 0;
while(*source)
{
if (*source == '/')
{
++count;
if (count == 4)
{
break;
}
}
++source;
}
return source;
}
int main()
{
const char* backup_path = "/home/ofy/real_2";
char temp1[] = "/home/dir1/dir2/dir3/dir4/dir5";
const char* s1 = temp1;
const char* s2 = getTargetPath(s1);
printf("\n");
char* full_path = (char*)malloc(strlen(backup_path) * sizeof(char));
strcpy(full_path, backup_path);
strcat(full_path, s2);
printf("%s\n", full_path);
return 0;
}
您沒有為full_path
分配足夠的空間:
char* full_path = (char*)malloc(strlen(backup_path) * sizeof(char));
它至少需要與backup_path
和s2
一樣長,加上 1 用於終止空字節,但您只有backup_path
足夠。 這導致您寫入超過已分配內存的末尾,從而調用未定義的行為。
對於未定義的行為,您無法預測您的程序會做什么。 它可能會崩潰,可能會輸出奇怪的結果,或者它可能看起來工作正常。 此外,進行看似無關的代碼更改可能會改變 UB 的表現方式。 這正是您刪除printf
調用時所看到的。 使用printf
程序“工作”,而沒有它程序崩潰。
要分配適當的空間量:
char* full_path = (char*)malloc(strlen(backup_path) + strlen(s2) + 1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.