c - 越界写入并不总是导致错误

标签 c memory malloc

<分区>

我编写了一个函数来将项目添加到我的日志文件中。变量 loglevs[]des 加起来超过 30 个字符(到目前为止)。当我使用下面的函数时,一切正常。

char *logitem (int loglev, const char *des) {

    extern const char *loglevs[];
    char *lld; // loglevel & description total 28 characters (7+1+20)

    lld = (char *) malloc((29) * sizeof(char));
    snprintf(lld, 29, "[%5s] %s", loglevs[loglev], des);

    return lld;

}

但是,当我使用 malloc(24) 而不是 malloc(29) 时,出现以下错误:

root@vm:/home/geohei/devel# prog
*** Error in `prog': malloc(): memory corruption: 0x0000000000853330 ***
Aborted (core dumped)

我原以为会在 malloc(28) 处得到错误。为什么它只显示在 malloc(24)?实际上,我可以在错误弹出之前转到 malloc(25)

我多次确认测试。

最佳答案

这是未定义的行为,定义在此 online c standard draft如下:

3.4.3

1 undefined behavior behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements

2 NOTE Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

所以程序可能会做任何事情,甚至忽略这种情况。但它也可能崩溃或报警:-)

关于c - 越界写入并不总是导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49265505/

相关文章:

c - 如何在 c/c++ 中将 char[3] 从 FLV 结构转换为 int

c - URL 名称解析未按预期运行

Python使用简单脚本过度使用内存

c - 错误消息地址的示例程序未被堆栈、malloc 或(最近)释放

c++ - 在 C++ 中显示访问冲突的错误

c - Linux 上的虚拟内存大小

MySQL填满内存并卡住

objective-c - 为什么可变对象不需要双指针?

c++ - 怎么realloc不行,malloc可以呢?

c - 将平台特定代码与嵌入式外设驱动程序的通用逻辑代码分开