printf() 在 C 中分配内存吗?

AdH*_*nem 3 c malloc printf heap-memory format-string

这个简单的方法只是创建一个动态大小为 n 的数组,并用值 0 ... n-1 对其进行初始化。它包含一个错误,malloc() 仅分配 n 而不是 sizeof(int) * n 字节:

int *make_array(size_t n) {
    int *result = malloc(n);

    for (int i = 0; i < n; ++i) {
        //printf("%d", i);
        result[i] = i;
    }

    return result;
}

int main() {
    int *result = make_array(8);

    for (int i = 0; i < 8; ++i) {
        printf("%d ", result[i]);
    }

    free(result);
}
Run Code Online (Sandbox Code Playgroud)

当您检查输出时,您会发现它会按预期打印一些数字,但最后的数字是乱码。然而,一旦我在循环中插入 printf() ,输出就出奇地正确,尽管分配仍然是错误的!是否有某种与 printf() 相关的内存分配?

Bra*_*est 6

严格来说,要回答标题中的问题,答案是这取决于实现。某些实现可能会分配内存,而其他实现可能不会。

尽管您的代码中还存在其他固有问题,我将在下面详细说明。


注:这最初是我对这个问题所做的一系列评论。我认为评论太多了,并将他们移至此答案。


当您检查输出时,您会发现它会按预期打印一些数字,但最后的数字是乱码。

我相信在使用分段内存模型的系统上,分配会“四舍五入”到一定的大小。也就是说,如果您分配 X 字节,您的程序确实将拥有这些 X 字节,但是,在 CPU 注意到您违反了边界并发送 SIGSEGV 之前,您还可以(错误地)运行这些 X 字节一段时间。

这很可能是您的程序在特定配置中没有崩溃的原因。请注意,您分配的 8 个字节将仅覆盖系统上的两个 int,其中sizeof (int)4 。其他 6 个 int 所需的其他 24 个字节不属于您的数组,因此任何内容都可以写入该空间,并且当您从该空间读取时,如果你的程序不先崩溃,你就会得到垃圾。

6这个数字很重要。记住它以供以后使用!

神奇的部分是,结果数组中将包含正确的数字,printf 实际上只是再次打印每个数字。但这确实改变了数组。

注意:以下是推测,我还假设您在 64 位系统上使用 glibc。我要添加这一点是因为我觉得它可能会帮助您理解为什么某些东西可能看起来工作正常但实际上不正确的可能原因。

它“神奇地正确”的原因很可能与通过 va_args 接收这些数字有关printfprintf可能正在填充刚刚超出数组物理边界的内存区域(因为 vprintf 正在分配内存来执行 print 所需的“itoa”操作i)。换句话说,那些“正确”的结果实际上只是“看似正确”的垃圾,但实际上,这正是 RAM 中的情况。如果您尝试更改int为,long同时保留 8 字节分配,您的程序将更有可能崩溃,因为long比 长int

malloc 的 glibc 实现有一个优化,每次用完堆时,它都会从内核分配整个页面。这使得速度更快,因为它不需要在每次分配时向内核请求更多内存,而是可以从“池”中获取可用内存,并在第一个“池”填满时创建另一个“池”。

也就是说,与堆栈一样,来自内存池的 malloc 堆指针往往是连续的(或至少非常接近)。这意味着 printf 对 malloc 的调用可能会出现在您为 int 数组分配的 8 个字节之后。但无论它如何工作,重点是,无论结果看起来多么“正确”,它们实际上只是垃圾,并且您正在调用未定义的行为,因此无法知道会发生什么,或者是否会发生这种情况。程序会在不同情况下执行其他操作,例如崩溃或产生意外行为。


所以我尝试使用和不使用 printf 来运行你的程序,两次结果都是错误的。

# without printf
$ ./a.out 
0 1 2 3 4 5 1041 0 
Run Code Online (Sandbox Code Playgroud)

不管出于什么原因,没有任何东西干扰记忆的保持2..5。然而,有些东西干扰了记忆的保持67。我的猜测是,这是 vprintf 的缓冲区,用于创建数字的字符串表示形式。1041将是文本,并将0是空终止符'\0'。即使它不是 vprintf 的结果,在填充和打印数组之间也有东西正在写入该地址。

# with printf
$ ./a.out
*** Error in `./a.out': free(): invalid next size (fast): 0x0000000000be4010 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x77725)[0x7f9e5a720725]
/lib/x86_64-linux-gnu/libc.so.6(+0x7ff4a)[0x7f9e5a728f4a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7f9e5a72cabc]
./a.out[0x400679]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f9e5a6c9830]
./a.out[0x4004e9]
======= Memory map: ========
00400000-00401000 r-xp 00000000 08:02 1573060                            /tmp/a.out
00600000-00601000 r--p 00000000 08:02 1573060                            /tmp/a.out
00601000-00602000 rw-p 00001000 08:02 1573060                            /tmp/a.out
00be4000-00c05000 rw-p 00000000 00:00 0                                  [heap]
7f9e54000000-7f9e54021000 rw-p 00000000 00:00 0 
7f9e54021000-7f9e58000000 ---p 00000000 00:00 0 
7f9e5a493000-7f9e5a4a9000 r-xp 00000000 08:02 7995396                    /lib/x86_64-linux-gnu/libgcc_s.so.1
7f9e5a4a9000-7f9e5a6a8000 ---p 00016000 08:02 7995396                    /lib/x86_64-linux-gnu/libgcc_s.so.1
7f9e5a6a8000-7f9e5a6a9000 rw-p 00015000 08:02 7995396                    /lib/x86_64-linux-gnu/libgcc_s.so.1
7f9e5a6a9000-7f9e5a869000 r-xp 00000000 08:02 7999934                    /lib/x86_64-linux-gnu/libc-2.23.so
7f9e5a869000-7f9e5aa68000 ---p 001c0000 08:02 7999934                    /lib/x86_64-linux-gnu/libc-2.23.so
7f9e5aa68000-7f9e5aa6c000 r--p 001bf000 08:02 7999934                    /lib/x86_64-linux-gnu/libc-2.23.so
7f9e5aa6c000-7f9e5aa6e000 rw-p 001c3000 08:02 7999934                    /lib/x86_64-linux-gnu/libc-2.23.so
7f9e5aa6e000-7f9e5aa72000 rw-p 00000000 00:00 0 
7f9e5aa72000-7f9e5aa98000 r-xp 00000000 08:02 7999123                    /lib/x86_64-linux-gnu/ld-2.23.so
7f9e5ac5e000-7f9e5ac61000 rw-p 00000000 00:00 0 
7f9e5ac94000-7f9e5ac97000 rw-p 00000000 00:00 0 
7f9e5ac97000-7f9e5ac98000 r--p 00025000 08:02 7999123                    /lib/x86_64-linux-gnu/ld-2.23.so
7f9e5ac98000-7f9e5ac99000 rw-p 00026000 08:02 7999123                    /lib/x86_64-linux-gnu/ld-2.23.so
7f9e5ac99000-7f9e5ac9a000 rw-p 00000000 00:00 0 
7ffc30384000-7ffc303a5000 rw-p 00000000 00:00 0                          [stack]
7ffc303c9000-7ffc303cb000 r--p 00000000 00:00 0                          [vvar]
7ffc303cb000-7ffc303cd000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
012345670 1 2 3 4 5 6 7 Aborted
Run Code Online (Sandbox Code Playgroud)

这是有趣的部分。您在问题中没有提到您的程序是否崩溃。但当我运行它时,它崩溃了。难的

如果有可用的话,最好检查一下 valgrind。Valgrind 是一个有用的程序,可以报告您如何使用记忆。这是 valgrind 的输出:

$ valgrind ./a.out
==5991== Memcheck, a memory error detector
==5991== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==5991== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==5991== Command: ./a.out
==5991== 
==5991== Invalid write of size 4
==5991==    at 0x4005F2: make_array (in /tmp/a.out)
==5991==    by 0x40061A: main (in /tmp/a.out)
==5991==  Address 0x5203048 is 0 bytes after a block of size 8 alloc'd
==5991==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5991==    by 0x4005CD: make_array (in /tmp/a.out)
==5991==    by 0x40061A: main (in /tmp/a.out)
==5991== 
==5991== Invalid read of size 4
==5991==    at 0x40063C: main (in /tmp/a.out)
==5991==  Address 0x5203048 is 0 bytes after a block of size 8 alloc'd
==5991==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5991==    by 0x4005CD: make_array (in /tmp/a.out)
==5991==    by 0x40061A: main (in /tmp/a.out)
==5991== 
0 1 2 3 4 5 6 7 ==5991== 
==5991== HEAP SUMMARY:
==5991==     in use at exit: 0 bytes in 0 blocks
==5991==   total heap usage: 2 allocs, 2 frees, 1,032 bytes allocated
==5991== 
==5991== All heap blocks were freed -- no leaks are possible
==5991== 
==5991== For counts of detected and suppressed errors, rerun with: -v
==5991== ERROR SUMMARY: 12 errors from 2 contexts (suppressed: 0 from 0)
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,valgrind 报告您有一个invalid write of size 4和一个invalid read of size 4(4 字节是我系统上 int 的大小)。它还提到您正在读取大小为 0 的块,该块位于大小为 8 的块(您分配的块)之后。这告诉你,你正在穿过阵列并进入垃圾区。您可能会注意到的另一件事是它从 2 个上下文生成了 12 个错误。具体来说,写作上下文中有6 个错误,阅读上下文有6 个错误。正是我之前提到的未分配空间量。

这是更正后的代码:

#include <stdio.h>
#include <stdlib.h>

int *make_array(size_t n) {
    int *result = malloc(n * sizeof (int)); // Notice the sizeof (int)

    for (int i = 0; i < n; ++i)
        result[i] = i;

    return result;
}

int main() {
    int *result = make_array(8);

    for (int i = 0; i < 8; ++i)
        printf("%d ", result[i]);

    free(result);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是 valgrind 的输出:

$ valgrind ./a.out
==9931== Memcheck, a memory error detector
==9931== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==9931== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==9931== Command: ./a.out
==9931== 
0 1 2 3 4 5 6 7 ==9931== 
==9931== HEAP SUMMARY:
==9931==     in use at exit: 0 bytes in 0 blocks
==9931==   total heap usage: 2 allocs, 2 frees, 1,056 bytes allocated
==9931== 
==9931== All heap blocks were freed -- no leaks are possible
==9931== 
==9931== For counts of detected and suppressed errors, rerun with: -v
==9931== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Run Code Online (Sandbox Code Playgroud)

请注意,它没有报告错误并且结果是正确的。