ARM Technical Support Knowledge Articles

NULL POINTER COMPARE FAILS WHEN MIXING MEMORY TYPES

Applies to: C51 C Compiler

Answer


Information in this article applies to:


QUESTION

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);
}

ANSWER

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.

MORE INFORMATION

SEE ALSO

Article last edited on: 2005-07-18 18:49:56

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential