c ++中增量垃圾收集模拟的内存分配 [英] Memory allocation for incremental garbage collection simulation in c++

查看:96
本文介绍了c ++中增量垃圾收集模拟的内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在C ++或Java中模拟一个增量垃圾回收算法。

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

作为输入(键盘上的 stdin ),我会被要求为此代码分配一些内存。语法如下:

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

x = alloc(128KB);

我的问题:可以使用 malloc 为作业?还是有其他方法来分配内存?我有这个疑问,因为大小可以上升到GB的任务,所以使用 malloc 可能不是一个好主意,我想。

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.

推荐答案

首先,如果你想禁止一个巨大的内存分配,只是检查用户的输入值,但我不知道你认为多少内存一个巨大的记忆。我想你不用担心,因为如果内存分配失败,malloc和calloc将返回一个NULL指针。

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.

其次,你也可以使用'calloc'

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

void calloc(size_t num, size_t size);

'num'是分配的平均元素数,'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));

但是,如果你选择'calloc',你可以更逻辑地管理你的代码,按单位和计数的存储量。
此外,如果使用'calloc',您不需要使用memset将内存值设置为零。
'calloc'将自动将内存值设置为零。

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.

我希望本文能帮到你。

这篇关于c ++中增量垃圾收集模拟的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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