| |||||
Technical Support Support Resources
Product Information | C51: NULL POINTER COMPARE FAILS WHEN MIXING MEMORY TYPESInformation in this article applies to:
QUESTIONThe 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);
}
ANSWERThe 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 ALSOLast Reviewed: Monday, July 18, 2005 | ||||
| |||||