Keil Logo

C51: Null Pointer Compare Fails When Mixing Memory Types

Information in this article applies to:

  • C51 Version 7.02, or higher
  • CX51 Version 7.02, or higher


The following program was working with C51 Version 7.01 or earlier but fails in the current compiler version. It looks like the program keeps searching un-initialized memory.

Is there something wrong in my code?

typedef struct node {
  struct node xdata *next;
  int    key;
} node;

node xdata *find_node (node xdata *root, int key) {
  node *n = root;

  while (n) {
    if (n->key == key)  return (n);
    n = n->next;
  return (0);


The pointer n is a generic pointer, while all your other pointers are memory typed (xdata) pointers. When you are using consistent pointer definitions, your code will work fine (and even the code gets a lot more efficient).

So the following code will do what you expect:

node xdata *find_node (node xdata *root, int key) {
  node xdata *n = root;

  while (n) {
    if (n->key == key)  return (n);
    n = n->next;
  return (0);

The 8051 has a number of different address spaces (code, data, xdata). The C51 Compiler supports both memory specific pointers and generic pointers which can point to any address space. The ANSI C NULL pointer relies on the fact that the memory address 0 cannot be accessed on most systems. However, the 8051 XDATA space starts at address 0 and is a valid memory location which cannot be excluded.

In your code, you are intermixing generic pointers with memory typed pointers. The memory location X:0 is represented as 0x10000 in generic pointer format and, therefore, not 0. Since several users wrote unsafe code by intermixing generic and memory typed pointers, there was a special handling implemented in Compiler Version 7.01 or before. But even there, the NULL pointer comparison was not consistent. With the introduction of far pointers, this special handling was removed to avoid run-time problems with far pointers.


  • Refer to Pointers in the Cx51 User's Guide.


Last Reviewed: Thursday, February 25, 2021

Did this article provide the answer you needed?
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.