分配适当的内存大小

发布于 2025-01-05 00:24:10 字数 387 浏览 1 评论 0原文

我在程序中分配正确大小的内存时遇到问题。我执行以下操作:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苏别ゝ 2025-01-12 00:24:10

传递多个字节作为 sbrk 的参数。

在Linux中,sbrk的原型为:

void *sbrk(intptr_t increment);

http://www.kernel.org/doc/man-pages/online/pages/man2/brk.2.html

sbrk() 按增量字节增加程序的数据空间。

但正如评论中的一些人所补充的,如果您想动态分配内存,您需要寻找 malloc 函数,而不是 sbrkbrksbrk 是通常在内部用于实现 malloc 用户函数的系统调用。

Pass a number of bytes as the argument of sbrk.

In Linux, the prototype of sbrk is:

void *sbrk(intptr_t increment);

http://www.kernel.org/doc/man-pages/online/pages/man2/brk.2.html

sbrk() increments the program's data space by increment bytes.

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. brk and sbrk are syscalls that are usually used internally for the implementation of the malloc user function.

烟酉 2025-01-12 00:24:10

内核以页粒度管理进程内存。这意味着进程地址空间必须增长(或缩小)整数页。
因此,即使 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文