【问题标题】:Why does "malloc(): corrupted top size" error get fixed when I have printf() before/after it?为什么当我在它之前/之后有 printf() 时,“malloc():损坏的最大尺寸”错误得到修复?
【发布时间】:2019-07-02 15:35:28
【问题描述】:

给定一个绝对路径,我试图获取某个目录之后的部分。 getTargetPath 函数可以做到这一点,当我编译并运行下面的代码时,代码会给我预期的输出。

问题是当我在 main 中删除 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 中是否有空终止符的空间?
  • 实际上,它比这更糟糕,因为您还尝试将s2 连接到full_path 的末尾,并且您绝对不会为此留出空间。
  • @Christian Gibbons 我刚刚尝试为它分配更多空间并且它起作用了,但我的问题仍然是为什么让 printf 解决问题,或者至少隐藏它?
  • @OmerFY:未定义的行为未定义。我们不会弄清楚分配器的精确实现,只是为了告诉您在您滥用它后它是如何损坏的。答案是“不要滥用它”。
  • 未定义的行为是未定义的。与它推理是徒劳的。导致太阳变暗的未定义行为完全符合规范。

标签: c pointers malloc


【解决方案1】:

你没有为full_path分配足够的空间:

char* full_path = (char*)malloc(strlen(backup_path) * sizeof(char));

它至少需要和backup_path 一样长 s2,加上终止空字节的1,但你只需要backup_path。这会导致您写入超过调用undefined behavior 的分配内存的末尾。

对于未定义的行为,您无法预测您的程序会做什么。它可能会崩溃,它可能会输出奇怪的结果,或者它看起来可以正常工作。此外,进行看似无关的代码更改可能会改变 UB 的表现方式。这正是您在删除 printf 调用时所看到的。使用printf 程序“工作”,而没有它程序崩溃。

分配适当的空间:

char* full_path = (char*)malloc(strlen(backup_path) + strlen(s2) + 1);

【讨论】:

  • 非常感谢!
猜你喜欢
  • 2021-06-28
  • 2023-02-17
  • 2021-12-11
  • 2015-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多