0

I have following code

#include<stdio.h>
int main () {
        void *result[20];
        void *endptr;
        void *x;
        for (i = 0; i < 20; i++) {
                result[i] = malloc(10);
                printf("111 : %d\n",result[i]);
        }
        endptr= sbrk(0);
        printf("\n222 : %d\n",endptr);
        x = malloc(60); ----------- error
        return 0;
}

I want to print numeric value of all the void pointers and the count how many times sbrk function called form malloc?

If I print *endptr in printf statement it gives me error. Currently I think it prints address where memory is allocated. %x would just convert current value in hex and print right?

x = malloc(60) also gives error : void value not ignored as it ought to be How can I do that?

Thanks

user1079065
  • 2,085
  • 9
  • 30
  • 53

2 Answers2

2

sbrk(0) returns the current size of the "program break", which isn't actually a pointer, so dereferencing it will give an error.

http://en.wikipedia.org/wiki/Sbrk

http://pubs.opengroup.org/onlinepubs/007908799/xsh/brk.html

HungryBeagle
  • 262
  • 1
  • 13
  • As your links show, `sbrk(0)` returns the current break (not a size) which IS a pointer. As it points to one byte past the end of usable memory, dereferencing it will pretty much always give an error. – Chris Dodd Apr 15 '14 at 18:43
  • @chux: In the comment "If I print *endptr in printf it gives me error" – Chris Dodd Apr 15 '14 at 22:05
1

The proper way to print data pointers in C using printf is this (there is no format for code pointers):

printf("%p", pointer);

That should output the pointer in the best format for the platform, and can be read back by scanf.
Using any other format specifier for pointers is explicitly Undefined Behavior, anything may happen.

Also, there is no guarantee malloc() uses legacy sbrk() at all. And even if it does, it might be able to use available free blocks instead of having to call it. Next, there is no guarantee sbrk() points to valid storage, so dereferencing it is undefined behavior.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118