Memory allocation for incremental garbage collection simulation in c++

陌路散爱 提交于 2019-12-24 00:35:33

问题


I need to simulate an incremental garbage collection algorithm in C++ or Java. I had a doubt based on this.

As an input (stdin from keyboard), I will be asked to allocate some memory for this code. The syntax would be:

x = alloc(128KB);

My question: is it ok to use malloc for the assignment? Or is there any other way to allocate memory? I had this doubt because, the size can go up to GB for the assignment, so using malloc might not be a good idea I think.


回答1:


First of all, if you want to prohibit a huge memory allocation, just check users' input value, but I'm not sure how much memory you think as a huge memory. I think you don't worry about that, because if memory allocation failed, malloc and calloc will return a NULL pointer.

Secondly, you can also use 'calloc' for this case.

void calloc(size_t num, size_t size);

'num' is mean elements' count for allocation and 'size' is, of course, the size of element. Below codes have the same result.

ar = (int *)malloc(5 * sizeof(int));
ar = (int *)calloc(5, sizeof(int));

However, if you choose 'calloc', you may manage more logically your code, since you can divide memory quantity by unit and count. Also, if you use 'calloc', you don't need to use memset for setting memory value to zero. 'calloc' set automatically memory value to zero.

I hope this article can help you.




回答2:


malloc can allocate as much memory as you wish provided you don't go past ulimits. Give the following a go to test it out:

#include <stdlib.h>
#include <string.h>

#define ONEGB (size_t)(1073741824)

int main() {
    char *p;
    p = malloc(ONEGB);
    if (!p) {
        perror("malloc");
    }
    else {
        memset(p, 0, ONEGB);
    }
    return 0;
}


来源:https://stackoverflow.com/questions/16474393/memory-allocation-for-incremental-garbage-collection-simulation-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!