c - 使用 realloc 填充内存

标签 c malloc realloc

这个问题可能看起来有点微不足道,我正在尝试用 C 编写一个程序,它在 OOM 被调用并杀死它之前尽可能多地消耗内存。虽然,我最初使用 malloc() 和 memset( ), 这次我决定尝试 realloc()。我这样做纯粹是为了学习目的,因为我是 C 的新手。

我打算在每次调用 realloc() 和 memset() 时分配 1MB。当我运行此程序以分配 20MB 时:

1) 我不明白为什么在输出中有些地址是相同的 (2-4) (5-10) & (11-20) ?它们不应该各不相同吗?

2) 我的程序真的消耗了 20MB 内存吗?我确实通过 Valgrind 运行它,它说“1 个 block 中的 22,020,096 个字节肯定丢失在丢失记录 1 of 1 中”

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>
#include <unistd.h>

int main (int argc,char **argv) {
char *ptr;
int max = 0;
int max_write;
int sleep_time;
size_t size = 1048576;
if (argc > 1) {
    sleep_time = (argv[2] ? atoi(argv[2]) : 2 ); 
    max_write  = (argv[1] ? atoi(argv[1]) : 1000);
    printf (" + To Write: %d,%d\n",max_write,sleep_time);
}
ptr = (char *) calloc (1,size);
if (ptr == NULL) {
    perror("calloc Error:");
}
printf(" + Allocation: %p\n",ptr);
do { 
    max++;
    size += (1048576);
    ptr = (char *) realloc (ptr,size);
    if (ptr == NULL) {
        perror("realloc Error:");
    }
    memset(ptr,0,size);
    printf(" + Pointer: %p / Memory: %d\n",ptr,max);
} while (max != max_write);
//
return(0);
}



OUTPUT:
./eatmemory 20 
+ Allocation: 0x7f2bb6b12010
+ Pointer: 0x7f2bb6451010 / Memory: 1
+ Pointer: 0x7f2bb6150010 / Memory: 2
+ Pointer: 0x7f2bb6150010 / Memory: 3
+ Pointer: 0x7f2bb6150010 / Memory: 4
+ Pointer: 0x7f2bb5b4f010 / Memory: 5
+ Pointer: 0x7f2bb5b4f010 / Memory: 6
+ Pointer: 0x7f2bb5b4f010 / Memory: 7
+ Pointer: 0x7f2bb5b4f010 / Memory: 8
+ Pointer: 0x7f2bb5b4f010 / Memory: 9
+ Pointer: 0x7f2bb5b4f010 / Memory: 10
+ Pointer: 0x7f2bb4f4e010 / Memory: 11
+ Pointer: 0x7f2bb4f4e010 / Memory: 12
+ Pointer: 0x7f2bb4f4e010 / Memory: 13
+ Pointer: 0x7f2bb4f4e010 / Memory: 14
+ Pointer: 0x7f2bb4f4e010 / Memory: 15
+ Pointer: 0x7f2bb4f4e010 / Memory: 16
+ Pointer: 0x7f2bb4f4e010 / Memory: 17
+ Pointer: 0x7f2bb4f4e010 / Memory: 18
+ Pointer: 0x7f2bb4f4e010 / Memory: 19
+ Pointer: 0x7f2bb4f4e010 / Memory: 20

最佳答案

1) I dont understand why in the output some of the address are the same (2-4) (5-10) & (11-20) ?Shouldn't each one of them be different.

正如其他人已经指出的那样,realloc 不一定要移动现有的内存块,而可能只是扩展它。

2) Is my program really consuming 20MB of memory? I did run it through Valgrind and it says "22,020,096 bytes in 1 blocks are definitely lost in loss record 1 of 1"

这在某种程度上是特定于实现的,但您通常最终会申请比您要求的更多的内存。首先,free 需要一些关于如何将内存与相邻的空闲 block 合并的元数据。此信息通常位于 alloc/realloc 将返回的地址之前的几个字节中。此外,内存的组织方式可能不允许分配任意大小,因此 malloc 只会返回最适合的内存。

关于c - 使用 realloc 填充内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26454504/

相关文章:

c - 如何正确地 malloc C 中的结构

c - 带有用户输入的二维数组

c - strtok 函数无法正常运行

c - SiftDescriptorExtractor 导致内存泄漏

c - 主要 : malloc. c :2372: sysmalloc: Assertion . .. 失败

c - 重新分配一个字符串数组

linux - 使用 valgrind 查找不断增长的 realloc

c - 重新分配() : invalid next size in C

c - X, Y, XY 为什么这在 gcc 中有效?

c - 数组 C 的动态内存分配