Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!iuvax!bobmon From: bobmon@iuvax.cs.indiana.edu (RAMontante) Newsgroups: comp.sys.ibm.pc Subject: Re: TC function returns rubbish. why? Message-ID: <31004@iuvax.cs.indiana.edu> Date: 7 Dec 89 14:14:56 GMT Reply-To: bobmon@iuvax.cs.indiana.edu (RAMontante) Distribution: na Organization: malkaryotic Lines: 41 burleigh@cica.cica.indiana.edu (Frank Burleigh) <272@cica.cica.indiana.edu> : - -char *make_fn( char * file_name ) -{ - int i; - char *w, *p = file_name; - char name[13]; - - for( w = name; *p; p++ ) - if( *p != ' ' ) - *w++ = *p; /*don't copy ws*/ - *w = '\0'; - return name; -} Your `name[]' array is an automatic variable, created on the stack. Thus it is guaranteed to be valid *only while make_fn() is active*. Once control returns to the caller that storage may be legally trashed. This isn't peculiar to Turbo C, it's a property of C itself (and of most languages that can distinguish between "temporary" local storage and "permanent" global storage). Library functions such as ctime() avoid this same problem by making the string storage be static data. Such storage stays put, until a subsequent function call overwrites it. Another choice is to let the caller supply the workspace --- this works better when the new string is of varying length. Try this: char *make_fn( char * file_name ) { static char name[13], *w; for( w = name; *file_name; file_name++ ) if( *file_name != ' ' ) *w++ = *file_name; /* copy only non-blanks */ *w = '\0'; return name; }