Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does malloc() have a maximum return value?

Tags:

c

pointers

memory

Does the size_t value of the virtual memory pointer returned by malloc() have an upper boundary?

I am wondering whether I can safely set the most significant bit of a 64 bits pointer to indicate that this is not a pointer but a literal integer instead.

like image 718
ezorita Avatar asked May 15 '15 10:05

ezorita


2 Answers

malloc returns a void* not an integer. Casting a pointer to an integer is not giving you the (virtual memory) address, but some value that has to adhere to the semantics as defined in the C language standard (0 for a null pointer and adding and subtracting is related to pointer arithmetic), but that's about it.

You must make no assumptions whatsoever about the values of pointers-cast-to-integers other than that. As a matter of fact a C implementation may very well be in its right to tag non-null pointer cast to integer with some internal information in the upper bits.

like image 150
datenwolf Avatar answered Nov 15 '22 09:11

datenwolf


As @datenwolf's answer states, you can't make any assumptions about how malloc is providing you the memory address. The MSB may well contain important bits that you could overwrite, if you attempted to use them to store meta data. I have worked on a 32-bit system that returned addresses with bits set in the MSB of addresses (not from malloc, but other system specific memory allocation functions).

However, it is guaranteed that malloc will return an address that is suitably aligned for your system. For example, on a 32-bit system, you'll get a 4-byte aligned pointer, and on 64-bit, you'll get an 8-byte aligned pointer. This means that you are guaranteed that the lower 2 or 3 bits respectively will be zero. You could increase the number of guaranteed bits by using memalign instead. It essentially is the same effect as storing meta data in the most significant bit. To get/set the literal, you can just up/down shift it into the remaining bits.

However, I wouldn't suggest either method. Save yourself some heartache, and allocate just a little more memory to store the flag. Unless you've got billions of them, it's really not worth it.

like image 26
MuertoExcobito Avatar answered Nov 15 '22 10:11

MuertoExcobito