C:我试图使用 malloc 和 realloc 查找堆的大小,但得到无限,我的程序的确切解决方案是什么

标签 c heap-memory

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

int main() { 
    int *p;
    int m=40;
    p=(int *)malloc(sizeof(int)*10);
    while(realloc(p,10*sizeof(int))
        m=m+40;
    printf("Number of bytes allocated for heap",m);
}

这个程序有什么问题

最佳答案

realloc(p,10*sizeof(int) 始终分配相同范围的内存。将其更改为 p = realloc(p,m*sizeof(int)。如果 realloc 成功,则通过其返回值返回指向新动态内存的指针,并将内存指针传递给它被释放(指针后面的数据从旧内存移动到新内存)。如果realloc分配内存失败,它返回NULL,没有分配内存,也没有内存被释放。此外,您应该始终释放分配的内存。像这样调整您的代码:

int main() { 
    int *p = NULL;
    int  m = 40;
    int *newP;
    do
    {
        newP = realloc( p, m*sizeof( int ) );
        if ( newP != NULL )
            p = newP;
        m = m+40;
    }
    while ( newP != NULL );
    free( p );
    printf("Number of bytes allocated for heap",m);
}

关于C:我试图使用 malloc 和 realloc 查找堆的大小,但得到无限,我的程序的确切解决方案是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34906606/

相关文章:

c - 在 C 中将矩阵作为参数传递不起作用

c - 我们如何在 c 程序中获取 .exe 文件的完整路径?

pointers - Rust 如何知道哪些类型拥有资源?

c++ - HeapAlloc 簿记

c++ - 谁负责C++中的栈和堆?

C如何判断一个char**占用多少内存

c# - 大O分析。非负数组中的最大整数

ios - 将从 Homebrew 下载的 C 库链接到 Xcode 项目时出错

c - 为什么 call 函数中的 if else 不适用于 do while 函数?

java.lang.OutOfMemoryError : Java heap space when using this short program to Remove title bar 错误