我正在尝试将一个应用程序从 Linux 移植到 Mac Os X (leopard),但是当我执行它时,我收到以下错误消息:malloc: *** error for object 0x100160 : double free
.
我用下面的代码重现了这个问题:
//main.cpp
#include <stdio.h>
#include <wchar.h>
int main(int argc, char*argv[])
{
wchar_t *b=NULL;
printf("a=%ls, b=%ls \n", L"a", b);
}
用 gcc 编译:
gcc main.cpp -o test
执行结果:
a=a, b=(null)
test (5337) malloc: *** error for object 0x100160 : double free
*** set a breakpoint in malloc_error_break to debug
这很奇怪,因为如果我使用这一行:printf("a=%ls, b=%ls", b, b)
,不会打印任何错误。
此外,我不能使用 wprintf(L"a=%ls, b=%ls", a, b)
。
在 Fedora 13 上,这个程序不会打印任何错误。
这是一个 printf 错误吗? 我怎样才能消除这个错误?
最佳答案
您不能将 NULL 指针打印为字符串,这是未定义的行为。来自 C99 标准,§7.19.6.1/8
The conversion specifiers and their meanings are:
...
s If nol
length modifier is present, the argument shall be a pointer to the initial element of an array of character type. ...If an
l
length modifier is present, the argument shall be a pointer to the initial element of an array ofwchar_t
type.
由于未明确允许使用 NULL 指针,因此不允许使用它们。您应该将代码更改为:
printf("a=%ls, b=%ls \n", L"a", b ? b : L"(null)");
关于c - 分配 : error double free with printf and a NULL wchar_t*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4726651/