|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Generate data entry and reporting .NET Web apps in minutes, straight from your database. Read our FREE whitepaper “Build Web 2.0 Applications Without Hand-Coding” Download now! |
|
#1
|
|||
|
|||
|
I have one problem with NULL pointer checking, i am creating one strcut pointer like this
struct node *root; now i am calling one function and pass the address of this pointer to it as a parameter insert(&root , key); in this function i check if root is NULL or not? struct node * insert(struct node **n, int d) { if (!(*n)) { if (!((*n) = malloc(sizeof(struct node)))) { return NULL; } (*n)->left = (*n)->right = NULL; (*n)->d = d; return *n; } if (KEY(d) < KEY((*n)->d)) { return insert(&(*n)->left, d); } if (KEY(d) > KEY((*n)->d)) { return insert(&(*n)->right, d); } return NULL; } now in the very first call to this function, *n is not NULL and instead of going into if loop for memory allocation, tries to do recursion and program fails giving memory access error. now if i haven't assigend anything to root, how come it is not NULL? |
|
#2
|
||||
|
||||
|
Quote:
An equally valid question would be, "if I haven't assigned anything to root, how come it is not 20?" It's the same thing, really. Until you actually assign a value to root, its value is undefined. And quite likely anthing but NULL.
__________________
"A poor programmer is he who blames his tools." http://analyser.oli.tudelft.nl/ |
|
#3
|
|||
|
|||
|
you could always try passing the node normally, and then using "this" (without qoutes of course). this is a pointer to any data structure. it is automatically assigned to any data structure, even if it is user defined.
pass the node by reference and then try if(this == NULL) |
|
#4
|
|||
|
|||
|
you cannot assume that ' struct node *root; ' will initialize root to NULL. since it is an uninitialized pointer you need to explicitly assign NULL to it before going fwd.
hope that helps. |
|
#5
|
|||
|
|||
|
m shah,
You might try a little switch in how you allocate memory for structures. When you allocate a block of memory, instead of using malloc() try calloc(), which initializes it's memory to 0. I now use calloc exclusively, and I have a lot fewer crashes. After that you only need to make sure that you're getting the right size, and your code will be quite trouble-free.
__________________
Clay Dowling Lazarus Notes Articles and commentary on web development http://www.lazarusid.com/notes/ |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > NULL Pointer mystery in C |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|