Mail Archives: djgpp/1994/12/10/16:20:46
>> 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 -