为什么 mprobe 在检查字符串文字时会失败?

Why does mprobe fail when checking string literals?

为了确保我实现的数据结构在功能上是合理的,我使用 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 吗?

enum mcheck_status mprobe(void *ptr);

[...]

The mprobe() function performs a consistency check on the block of allocated memory pointed to by 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;
      |                                   ~~~~~~^~~~~