3

I am writing my own functions for malloc and free in C for an assignment. I need to take advantage of the C sbrk() wrapper function. From what I understand sbrk() increments the program's 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 code snippet:

#define BLOCK_SIZE 20

int x;

x = (int)sbrk(BLOCK_SIZE + 4);

I get the compiler error warning: cast from pointer to integer of different size. Why is this and is there anyway I can cast the address pointed to by sbrk() to an int?

trincot
  • 317,000
  • 35
  • 244
  • 286
user3268401
  • 319
  • 1
  • 7
  • 21
  • 3
    Is there any reason not to use `void *x;` ? If you really want an integral type there is `intptr_t x = (intptr_t)sbrk...;` from `` – M.M Mar 25 '14 at 03:16
  • Because int is 32 bits, pointer is 64 bits. try use long int. try check sizeof(int) and sizeof(void*) – Jaemok Lee Mar 25 '14 at 03:24

1 Answers1

13

I get the compiler error warning: cast from pointer to integer of different size.
Why is this

Because pointer and int may have different length, for example, on 64-bit system, sizeof(void *) (i.e. length of pointer) usually is 8, but sizeof(int) usually is 4. In this case, if you cast a pointer to an int and cast it back, you will get a invalid pointer instead of the original pointer.

and is there anyway I can cast the address pointed to by sbrk() to an int?

If you really need to cast a pointer to an integer, you should cast it to an intptr_t or uintptr_t, from <stdint.h>.


From <stdint.h>(P):

  • Integer types capable of holding object pointers

The following type designates a signed integer type with the property that any valid pointer to void can be converted to this type, then converted back to a pointer to void, and the result will compare equal to the original pointer: intptr_t

The following type designates an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to a pointer to void, and the result will compare equal to the original pointer: uintptr_t

On XSI-conformant systems, the intptr_t and uintptr_t types are required; otherwise, they are optional.

Community
  • 1
  • 1
Lee Duhem
  • 14,695
  • 3
  • 29
  • 47
  • I tried casting it to an `intptr_t` and it compiled. The reason I'm trying to cast it to an `int` is so that I can see if there is any more space left on the heap. If in my code snippet above, x is less than 0, then there is no more space on the heap. – user3268401 Mar 25 '14 at 03:38