www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1994/12/10/16:20:46

Date: Sat, 10 Dec 1994 13:03:54 -0500
From: davis AT amy DOT tch DOT harvard DOT edu ("John E. Davis")
To: djgpp AT sun DOT soe DOT clarkson DOT edu, endre AT alpha1 DOT obuda DOT kando DOT hu, frankie AT si DOT upc DOT es
Subject: Re: Strange crashes

>> 2. What's wrong with the following function?
> 
>> char* string(int n,char c)
>> {
>>         char* ts;
>>         ts=(char*)malloc(n+1);
>>         memset(ts,c,n);
>>         ts[n]=0;
>>         return(ts);
>> }
>
>I think the wrong stuff here is the way the variable is declared.
>If you want to return an allocated variable you should make it static.
>Variables declared in functions are stored in the stack. So when the
>function returns the space allocated in the stack is released.

No, that is not it.  He is returning the _value_ of the variable.  You are
thinking of something like: return &ts; (the address of the value) which is
definitely a no-no if ts is a local automatic variable.

You should do something like:

     if (n < 0) return NULL;
     if (NULL != (ts = (char *) malloc (n + 1)))
       {
          memset (ts, c, n);
	  ts [n] = 0;
       }
     return ts;
     
--John     

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019