Keil Logo

C51: Null Pointer Compare Fails With MALLOC and CALLOC


Information in this article applies to:

  • C51 All Versions
  • CX51 All Versions

QUESTION

The pointer NULL comparison in the following code never becomes true. However, the loop should allocate all available memory.

void *p;

while (1)  {
  p = malloc (100);
  if (p == NULL)  return;
}

Is there a mistake in my code?

ANSWER

The malloc function returns a memory specific pointer to xdata. When you convert the pointer to a generic pointer, the pointer value is 0x10000. Therefore, this is not a NULL pointer anymore.

When you define the pointer as a memory typed pointer, the code works:

void xdata *p;

while (1)  {
  p = malloc (100);
  if (p == NULL)  return;
}

SEE ALSO


Last Reviewed: Thursday, February 25, 2021


Did this article provide the answer you needed?
 
Yes
No
Not Sure
 
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.