【问题标题】:Why does mprobe fail when checking string literals?为什么检查字符串文字时 mprobe 会失败?
【发布时间】:2023-03-21 02:34:01
【问题描述】:

为了确保我实现的数据结构功能健全,我使用mcheck 编写了一个测试文件,以确保我在分配的内存范围内工作。但是,当尝试在字符串文字上使用mprobe()(并在开头调用mcheck(NULL))时,程序总是以MCHECK_HEAD 中止。

我用我能想到的最小程序尝试了这个:

#include <mcheck.h>
#include <stdio.h>

int main()
{

    mcheck(NULL);
    mprobe("test");

    exit(0);

}

结果如下:

$ gcc test.c -lmcheck
$ ./a.out
memory clobbered before allocated block
Aborted (core dumped)

因此,mcheck 似乎在遇到字符串文字时都会失败,认为前面的内存已被修改。为什么?是不是因为字符串没有明确malloced?

【问题讨论】:

  • “分配的内存”是指malloc家族函数分配的内存

标签: c gcc memory-management heap-memory


【解决方案1】:
enum mcheck_status mprobe(void *ptr);

[...]

mprobe() 函数对ptr 指向的已分配内存块执行一致性检查。

字符串文字不是指向已分配内存的指针。 C 标准非常严格地将已分配存储定义为使用malloccallocrealloc 等分配的存储。 POSIX 扩展了列表,例如与strdup。另一方面,字符串文字是具有静态存储持续时间的不可修改的 array 字符,尽管它没有 const 元素类型,这就是您没有收到警告的原因.试试:

char *foo = "test";
const char *bar = "test";
mprobe(foo);
mprobe(bar);

和编译器reports a constraint violation编译后一个调用:

<source>: In function 'main':
<source>:12:12: warning: passing argument 1 of 'mprobe' discards 'const' qualifier
from pointer target type [-Wdiscarded-qualifiers]
   12 |     mprobe(bar);
      |            ^~~
In file included from <source>:1:
/usr/include/mcheck.h:53:41: note: expected 'void *' but argument is of
type 'const char *'
   53 | extern enum mcheck_status mprobe (void *__ptr) __THROW;
      |                                   ~~~~~~^~~~~

【讨论】:

  • 我明白了。那么所有的常量指针在功能上都被认为是“分配的内存”吗?
  • @JSONBrody 这不是“分配的内存块”,字符串文字一起存在于内存段中,它们不是单独分配的。文档还声明内存必须已使用 malloc 或 realloc 分配。
猜你喜欢
  • 2015-03-05
  • 1970-01-01
  • 1970-01-01
  • 2020-05-24
  • 1970-01-01
  • 2011-04-04
  • 2015-08-17
  • 2010-10-22
  • 1970-01-01
相关资源
最近更新 更多