分配适当的内存大小
我在程序中分配正确大小的内存时遇到问题。我执行以下操作:
void * ptr = sbrk(sizeof(void *)+sizeof(unsigned int));
当我这样做时,我认为它向堆添加了太多内存,因为它以 void* 为单位而不是字节来分配内存。我如何告诉它我希望 sizeof(whatever) 表示 whatever 字节而不是 whatever 其他单位?
编辑:
我见过其他人将东西转换为字符,以便编译器采用字节大小。如果 sizeof(unsigned int) 是 4 个字节,但我使用的类型是 void *,编译器是否会中断 void * 大小的 4 倍而不是 4 个字节?
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. How do I tell it that I want sizeof(whatever) to mean whatever bytes instead of whatever other units?
EDIT:
I have seen other people cast things as a char so that the compiler takes the size in bytes. 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
传递多个字节作为 sbrk 的参数。
在Linux中,
sbrk
的原型为:http://www.kernel.org/doc/man-pages/online/pages/man2/brk.2.html
但正如评论中的一些人所补充的,如果您想动态分配内存,您需要寻找
malloc
函数,而不是sbrk
。brk
和sbrk
是通常在内部用于实现malloc
用户函数的系统调用。Pass a number of bytes as the argument of
sbrk
.In Linux, the prototype of
sbrk
is:http://www.kernel.org/doc/man-pages/online/pages/man2/brk.2.html
But as some people in the comments added, if you want to dynamically allocate memory you are looking for the
malloc
function and notsbrk
.brk
andsbrk
are syscalls that are usually used internally for the implementation of themalloc
user function.内核以页粒度管理进程内存。这意味着进程地址空间必须增长(或缩小)整数页。
因此,即使
sbrk
获取了多个字节,它也会向进程添加至少一页。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.