gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:47:20 25 4
gpt4 key购买 nike

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

关于c - 为什么 mprobe 在检查字符串文字时会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58161561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com