[comp.lang.c] turbo C initializing pointer problem

dbearly@vax1.tcd.ie (01/15/91)

I seem to be having a few problems with pointers in TC 2.0.
What happens is I have a pointer to a data structure 
( a doubly linked list) which contains character string 
pointers etc.
At compile time I get the warning 'possible use before initialization'
on the first element of the list and then have problems with the 
first call to strcpy to this element (ie it doesn't work).

I have tried initializing the element to NULL, which gets rid of the
warning and strcpy problems, but when the program terminates I get a
'Null pointer assignment' message.

	What can I do ??

			Dom.    8-{0

dbearly@vax1.tcd.ie
dbearly@unix1.tcd.ie

volpe@camelback.crd.ge.com (Christopher R Volpe) (01/16/91)

In article <1991Jan15.111940.7464@vax1.tcd.ie>, dbearly@vax1.tcd.ie writes:
|>I seem to be having a few problems with pointers in TC 2.0.
|>What happens is I have a pointer to a data structure 
|>( a doubly linked list) which contains character string 
|>pointers etc.
|>At compile time I get the warning 'possible use before initialization'
|>on the first element of the list and then have problems with the 
|>first call to strcpy to this element (ie it doesn't work).
|>
|>I have tried initializing the element to NULL, which gets rid of the
|>warning and strcpy problems, but when the program terminates I get a
|>'Null pointer assignment' message.
|>
|>	What can I do ??

You can avoid copying strings into nowhere. The value you pass to
strcpy as the destination of the copy must be the address of some 
valid storage. It can't be NULL or some uninitialized value. I assume your
struct looks something like this:
           struct node {
                char *mystring;
                struct node *next,*prev;
           };
If you leave "mystring" uninitialized, you don't know where you're copying
to, which is likely to cause problems. If you initialize it to NULL, you're
copying to nowhere. It should be initialized to some storage that can 
hold the source string. For example:
           struct node mynode;
           mynode.mystring = malloc((size_t) MAX_STRING_SIZE_I_NEED);
           strcpy(mynode.mystring,"some string");

When mallocing storage, make sure you malloc enough to hold the 
terminating '\0' as well as all the characters you need to hold.

It would probably be a good idea to read the FAQ list and Chapter 5 of K&R.

|>
|>			Dom.    8-{0
|>
|>dbearly@vax1.tcd.ie
|>dbearly@unix1.tcd.ie
                  
==================
Chris Volpe
G.E. Corporate R&D
volpecr@crd.ge.com