Memory allocation for incremental garbage collecti

2019-07-24 20:00发布

问题:

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;
}