This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Malloc

I'm using the MCBx51 V2.1 prototype Board with the Keil uVision2 software, but I have some problems with memory allocation.

This is the code that i had typed.

p = malloc (1000);


if (p == NULL)
printf ("Not enough memory space\n");
else
printf ("Memory allocated\n");

p[0] = 0x01;
p[1] = 0x03;

printf("%c",p[0]);
printf("%c",p[1]);

How come the output from the serial port is 0x0100 instead of 0x0103?

Can anyone help me...

Thanks...

Parents
  • Remember that malloc returns an "abstract" pointer - it's just an address with no type associated (void *)
    Therefore you should (in C++, must) cast its return value to a "real" type; eg,

    p = (char*) malloc( 1000 );

    Anyway, I suspect that the root of your problem is that good old chestnut, the printf parameter size:
    unless you tell it otherwise, it's expecting its parameters to be ints - and will promote your char values to get it!

    You need:
    printf( "%c", (char)p[0] );
    printf( "%c", (char)p[1] );

Reply
  • Remember that malloc returns an "abstract" pointer - it's just an address with no type associated (void *)
    Therefore you should (in C++, must) cast its return value to a "real" type; eg,

    p = (char*) malloc( 1000 );

    Anyway, I suspect that the root of your problem is that good old chestnut, the printf parameter size:
    unless you tell it otherwise, it's expecting its parameters to be ints - and will promote your char values to get it!

    You need:
    printf( "%c", (char)p[0] );
    printf( "%c", (char)p[1] );

Children