Hi all,

I am writing a program that uses XPath to search an XML document. There are several sanity checks that need to be performed before performing the search. To clean up the function, I am trying to put the sanity checks in a separate function. The problem is that this entails initializing the strucutures in the external function. I have come to realize that, even though they are pointers, if they are initialized in the external function, their value is not kept once they return to the main fucntion.
I have created a simple example to illustrate the point. In the following program, I define a "book" structure with 3 properties. In main(), I declare two "book" variables, one is initialized within main(), the other is initialized in an external function. The one that is initialized in the external function is no longer valid once it returns to main(). Can anyone suggest how to address this problem?



Code:
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int npages ;
    char* color ;
    int isbn ;
} book ;

int set_isbn(book* elbook, book* elbook2) {
    elbook->isbn = 1234 ;

    elbook2 = malloc(sizeof(book)) ;
    elbook2->isbn = 789 ;
    elbook2->color = "brown " ;
    elbook2->npages = 5 ;

    printf("The book has %d pages, its %s, and its isbn is %d\n", elbook2->npages, elbook2->color, elbook2->isbn) ;

    return 0 ;

}

int main()
{
    book* thebook = malloc(sizeof(book)) ;
    book* thebook2 = NULL ;
    thebook->color = "white" ;
    thebook->npages = 4 ;

    set_isbn(thebook , thebook2) ;
    printf("The book has %d pages, its %s, and its isbn is %d\n", thebook->npages, thebook->color, thebook->isbn) ;
    printf("The book has %d pages, its %s, and its isbn is %d\n", thebook2->npages, thebook2->color, thebook2->isbn) $
    return 0 ;
}
The output:

Code:
The book has 5 pages, its brown , and its isbn is 789
The book has 4 pages, its white, and its isbn is 1234
zsh: segmentation fault  ./a.out
The segfault is due to trying to access the memory location of thebook2, which is no longer valid.




Thanks,

JD