如何获得内存块长度的malloc后? [英] How to get memory block length after malloc?

查看:224
本文介绍了如何获得内存块长度的malloc后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我无法检索像Java中的简单。长度功能的分配的内存块的长度。不过,我现在知道,当的malloc()分配块,它分配额外的字节容纳包括块的大小为整数。此整数是位于该块的开始;的地址实际上返回给调用者指向的位置刚刚过去这个长度值。问题是,我无法访问该地址检索块长度。

I thought that I couldn't retrieve the length of an allocated memory block like the simple .length function in Java. However, I now know that when malloc() allocates the block, it allocates extra bytes to hold an integer containing the size of the block. This integer is located at the beginning of the block; the address actually returned to the caller points to the location just past this length value. The problem is, I can't access that address to retrieve the block length.

#include <stdlib.h>
#include <stdio.h>
int main(void)
{
        char *str;
        str = (char*) malloc(sizeof(char)*1000);
        int *length;
        length = str-4; /*because on 32 bit system, an int is 4 bytes long*/
        printf("Length of str:%d\n", *length);
        free(str);
}

**编辑:
我终于做到了。问题是,它不断给0作为长度,而不是我的系统上的大小,因为我的Ubuntu是64位。我改变STR-4 STR-8,和它的作品了。

** I finally did it. The problem is, it keeps giving 0 as the length instead of the size on my system is because my Ubuntu is 64 bit. I changed str-4 to str-8, and it works now.

如果我改变大小到2000年,它生产作为2017年的长度。然而,当我更改为3000,它给3009我使用的GCC。

If I change the size to 2000, it produces 2017 as the length. However, when I change to 3000, it gives 3009. I am using GCC.

推荐答案

你在做什么肯定是不对的。虽然这是几乎可以肯定,之前分配的块的大小有关,字即便如此,它可能包含了未使用的位一些额外的标志或信息。根据不同的实现,这个数据甚至可能在位,这将导致你阅读完全错误的长度。此外,它可能是小分配(如1〜32字节)被打包成无头特别小的块页,在这种情况下,分配的内存块前的字是另一个块的一部分,并没有任何意义相对于大小块你检查。

What you're doing is definitely wrong. While it's almost certain that the word just before the allocated block is related to the size, even so it probably contains some additional flags or information in the unused bits. Depending on the implementation, this data might even be in the high bits, which would cause you to read the entirely wrong length. Also it's possible that small allocations (e.g. 1 to 32 bytes) are packed into special small-block pages with no headers, in which case the word before the allocated block is just part of another block and has no meaning whatsoever in relation to the size of the block you're examining.

只要停止这种错误的和危险的追求。如果你需要知道的malloc 获得块的大小,你做错了什么。

Just stop this misguided and dangerous pursuit. If you need to know the size of a block obtained by malloc, you're doing something wrong.

这篇关于如何获得内存块长度的malloc后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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