Page 116 - Programming Microcontrollers in C
P. 116
Structures 101
statement of this code is a recursive call to treeprint() with the
pointer to the left child pointer as an argument. This recursive call will
cause control to propagate to the lowest and leftmost level of the tree. At
this time treeprint() will return normally, and the word pointed to
in the Tnode will be printed out by the printf() call. The program
will then start a recursive treeprint() to the right of this node.
Control will immediately go to the left side of the right branch and will
descend the lowest level and print out the word “found.” This routine
will repeat up and down until the whole tree content has been printed.
The function strsave() copies the word passed to it as an
argument into a save place and returns a pointer to this memory loca
tion to the calling program. C provides for dynamic allocation of
memory.
char *strsave(char *s) /* make a duplicate of s */
{
char *p;
p = (char *)malloc(strlen(s)+1);
if(p != NULL)
strcpy(p,s);
return p;
}
Up to this point, all memory access was to memory allocated by
declaration statements. With dynamic allocation, the program can
go to the operating system and request memory at any time. This
memory is from a memory area called the program heap. The first
call to allocate memory is malloc() shown above. The function
prototype for this function is found in stdlib.h , and the func
tion requires an argument that is the length of the memory space
needed. The program returns a pointer to the base type of the system,
chars, to the required block of memory. If there is not enough
memory available, the function returns a NULL pointer. C will never
return a valid NULL pointer. Therefore, if you have a C program call
that returns a pointer, the program can always test for a NULL pointer
to determine if the call succeeded. In the above code, it is assumed
that the calling program will check for the NULL pointer and deter
mine what to do.