[英]Allocating proper memory size
I am having an issue with allocating the right size of memory in my program. 我在程序中分配合适的内存大小时遇到问题。 I do the following:
我执行以下操作:
void * ptr = sbrk(sizeof(void *)+sizeof(unsigned int));
When I do this, I think it is adding too much memory to the heap because it is allocating it in units of void* instead of bytes. 当我这样做时,我认为它为堆添加了过多的内存,因为它以void *而不是字节为单位分配内存。 How do I tell it that I want sizeof( whatever ) to mean whatever bytes instead of whatever other units?
如何告诉我我想要sizeof( what )表示什么字节而不是其他任何单位?
EDIT: 编辑:
I have seen other people cast things as a char so that the compiler takes the size in bytes. 我已经看到其他人将事物转换为char,以便编译器采用字节大小。 If sizeof(unsigned int) is 4 bytes, but the type that I was using is void *, will the compiler break 4 times the size of a void * instead of 4 bytes?
如果sizeof(unsigned int)是4个字节,但是我使用的类型是void *,那么编译器会破坏void *大小的4倍而不是4个字节吗?
Pass a number of bytes as the argument of sbrk
. 传递多个字节作为
sbrk
的参数。
In Linux, the prototype of sbrk
is: 在Linux中,
sbrk
的原型为:
void *sbrk(intptr_t increment);
http://www.kernel.org/doc/man-pages/online/pages/man2/brk.2.html http://www.kernel.org/doc/man-pages/online/pages/man2/brk.2.html
sbrk() increments the program's data space by increment bytes.
sbrk()通过增加字节来增加程序的数据空间。
But as some people in the comments added, if you want to dynamically allocate memory you are looking for the malloc
function and not sbrk
. 但是正如某些人在注释中所添加的那样,如果要动态分配内存,则需要的是
malloc
函数而不是sbrk
。 brk
and sbrk
are syscalls that are usually used internally for the implementation of the malloc
user function. brk
和sbrk
是通常在内部用于实现malloc
用户功能的系统调用。
The kernel manages process memory in a page granularity. 内核以页面粒度管理进程内存。 This means the process address space must grow (or shrink) by a whole number of pages.
这意味着进程地址空间必须按页面总数增长(或缩小)。
So even though sbrk
gets a number of bytes, it would add at least one page to the process. 因此,即使
sbrk
获得了一定数量的字节,它仍将向该进程添加至少一页。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.