程序堆大小? [英] Program heap size?

查看:83
本文介绍了程序堆大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C语言编写的程序的最大堆大小是否已固定,或者如果我继续进行malloc-ing,它将在某个时候开始溢出?

Is the maximum heap size of a program in C fixed or if I keep malloc-ing it will at some point start to overflow?

代码:

 while(connectionOK) //connectionOK is the connection with server which might be forever
 {
    if(userlookup_IDNotFound(userID))
     user_struct* newuser = malloc(getsize(user_struct));
     setupUserAccount(newuser);
 }

如果重要的话,我正在ubuntu/linux中使用gcc. 我知道类似getrlimit的东西,但不确定它是否提供堆大小.尽管它确实为输入参数中的选项之一提供了默认的堆栈大小. 另外,valgrind可能是一个很好的工具,如此处>如何获取程序,但是如果堆溢出,我想动态打印一条错误消息. 我的理解是在过程创建开始时由操作系统分配的过程地址空间(如果需要它实际上允许使用整个内存),但是我不确定一旦请求它是否会动态分配更多的物理内存以获得额外的内存.

I am using gcc in ubuntu/ linux if that matters. I know something like getrlimit but not sure if it gives heap size. Although it does give the default stack size for one of the options in the input argument. Also valgrind is probably a good tool as suggested here how to get Heap size of a program but I want to dynamically print an error message if there is a heap overflow. My understanding was the process address space being allocated by the OS (which is literally allowed to use the whole memory if it wants to) at the beginning of the process creation but I am not sure if it is dynamically given more physical memory once it requests for additional memory.

推荐答案

堆永远不会溢出,它只会在某个时刻耗尽内存(通常在malloc()返回NULL时),因此要检查内存不足,只需检查一下malloc()调用的返回值.

The heap never overflows it just runs out of memory at a certain point (usually when malloc() returns NULL) So to detect out of memory just check the return value of the malloc() call.

if (newuser == NULL)
{
    printf("OOM\n");
    exit(1); /* exit if you want or can't handle being OOM */
}

malloc()在内部将向操作系统请求更多的内存,因此它会动态扩展,因此它的大小不是固定的,因为它会将不再需要的页面返回给操作系统,并在需要的任何给定时间请求更多的内存他们.

malloc() internally will request more memory from the OS so it expands dynamically so it's not really fixed size as it will give back pages to the OS that it no longer needs as well as requesting more at any given time that it requires them.

这篇关于程序堆大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆