Allocating a pointer to int
I am writing my own functions for malloc
and free
in C for assignment. I need to use the C wrapper function sbrk()
. From what I understand, it sbrk()
increases the program data space by the number of bytes passed as an argument and points to the location of the program break.
If I have the following piece of code:
#define BLOCK_SIZE 20
int x;
x = (int)sbrk(BLOCK_SIZE + 4);
I am getting a compiler error warning: cast from pointer to integer of different size
. Why is this so, anyway I can point the address sbrk()
to int
?
source to share
I am getting a compiler error warning: casts from pointer to variable size integer.
Why is this
Since the pointer and int
can have different lengths, for example on a 64-bit system, sizeof(void *)
(i.e. pointer length) is usually 8, but sizeof(int)
usually 4. In this case, if you draw a pointer to int
and discard it, you get an invalid pointer instead of the original pointer.
and still I can point the address that sbrk () points to to an int?
If you really need to cast a pointer to an integer, you must point it to intptr_t
or uintptr_t
, from <stdint.h>
.
From <stdint.h>(P)
:
- Integer types capable of holding object pointers
The following type denotes a signed integer type with the property that any valid pointer to void can be converted to that type, and then converted back to a pointer to void, and the result will be compared to the original pointer:
intptr_t
The following type denotes an unsigned integer type with the property that any valid pointer to void can be converted to that type, and then converted back to a pointer to void, and the result will be compared to the original pointer:
uintptr_t
On XSI-compatible systems, the types
intptr_t
and are requireduintptr_t
; otherwise, they are optional.
source to share