Auteur: Hendrik Boom Datum: Aan: dng Onderwerp: Re: [DNG] Making sense of C pointer syntax.
On Sat, Apr 02, 2016 at 10:55:53AM +0100, KatolaZ wrote: > On Fri, Apr 01, 2016 at 07:34:02PM -0400, Steve Litt wrote:
>
> [cut]
>
> >
> >
> > =========================================================
> > char * read_bbs(){
> > char rtrn[WAY_BIGGER_THAN_EVER_NEEDED];
> > strcpy(rtrn, grab_bbs_part1());
> > strcat(rtrn, grab_bbs_part2());
> > return(rtrn);
> > }
> >
> > result_string = read_bbs();
> > do_other_stuff();
> > use_result_string(result_string);
> > =========================================================
> >
> > Well, it worked 99.6% of the time, but once in a while the whole
> > program blew up. :-). I solved this intermittent on my third visit,
> > racked up probably 10 hours trying to fix it, and my problem probably
> > cost a couple hundred hours of keypuncher time before I fixed it.
> >
> > WAY_BIGGER_THAN_EVER_NEEDED really was way bigger than ever needed. Bad
> > programming, but that wasn't the problem.
> >
> > All I can say is I *never* made that mistake again.
> >
>
> Well, that one is a completely different beast... You never return a
> pointer to an automatic variable, unless it has been declared
> "static", for the simple reason that the variable does not exist any
> more when the function returns. Your code probably "worked" only
> because there was no call to any other functions in between (and thus
> the stack was magically unmodified), but otherwise that code should in
> general blow up pretty early, whatever the size of
> WAY_BIGGER_THAN_EVER_NEEDED...
The bigger WAY_BIGGER... is the lss often it would be likely to fail.
If the stack grows in the directio of lower memory addresses, the
beginning of rtrn would be farther from the caller's stack position,
and thus less likely to be overrun by other function calls.