5

I have a pointer returned from malloc. Which points to first byte of allocated size. For EX:

  void* p=malloc(34);

How to print the binary values contained in those 34 bytes. ?

Vishwanath gowda k
  • 1,675
  • 24
  • 26
  • char *p=(char*)malloc()...try with this it may work... – vinod Mar 10 '14 at 10:37
  • 1
    Nothing of interest is contained in these bytes until you write to them. When malloc returns, the pointer points to garbage until you do some writes into that memory. – Sergey Kalinichenko Mar 10 '14 at 10:38
  • 2
    @vinod Don't cast `malloc` (especially to a `char`) – Sergey Kalinichenko Mar 10 '14 at 10:38
  • @dasblinkenlight: I think markdown is affecting @vinod's comment, the italicised text runs right between where you'd expect two asterisks: `char *p = (char *) malloc()`... still, one shouldn't cast the result of malloc. – dreamlax Mar 10 '14 at 10:54
  • Not sure he want really to print in binary, but rather "see" what's in that allocated memory. – Jabberwocky Mar 10 '14 at 10:54

1 Answers1

6

You probably want this :

int i ;
void* p=malloc(34);

for (i = 0; i < 34; i++)
{
  unsigned char c = ((char*)p)[i] ;
  printf ("%02x ", c) ;
}

It doesn't print in binary (010011011) but in hexadecimal, but that's probably what you want.

But as stated in the comments you will get garbage values.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115