c - 分配 : error double free with printf and a NULL wchar_t*

标签 c macos gcc printf

我正在尝试将一个应用程序从 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 no l 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 of wchar_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/

相关文章:

objective-c - 使用 osx 10.11 sdk 构建时用于 64 位模式的 CopyCStringToPascal() 替代方案

c - 可移植数学 C 代码在 Linux 64 和 Windows 32 上表现不同

C可变宽度位域

c - 在C中获取大小为10^12的数组

c - 如何创建 CUDA makefile 以便在 CPU 中执行以测试 CPU FLOP?

c++ - 如何将 SQLite c 文件(合并)与 cpp 应用程序链接?

c - 为什么同一个结构体的大小在x86和arm同版本gcc中计算出来的不一样?

c - OpenCL 程序中的未知错误

macos - flutter 医生 : ERROR: Could not connect to lockdownd, 错误代码 -21

objective-c - 将 dylib 插入现有的包/可执行文件