:: Re: [DNG] Making sense of C pointer…
Page principale
Supprimer ce message
Répondre à ce message
Auteur: Steve Litt
Date:  
À: dng
Sujet: Re: [DNG] Making sense of C pointer syntax.
On Sat, 2 Apr 2016 10:55:53 +0100
KatolaZ <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);
> > =========================================================


[snip]

>
> Well, that one is a completely different beast...


Yes it is, isn't it? :-)


> You never return a
> pointer to an automatic variable,


How'd you learn that? I learned that by this particular incident, and I
*NEVER* did that again.

> unless it has been declared
> "static",


Yes. My "solution" was to prepend the variable declaration with the
word "static", and it never crashed again.

> 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...


It was a long time ago, and I don't have the code anymore, but I think
what happened was that in the function returning the automatic char*, I
had declared a lot of big automatic variables before the string I
returned, such that subsequent functions never declared enough to reach
that area of the stack, so although it was out of scope, it was left
alone.

However, once in a while a reeeeaaaaaly long piece of input data came
through, which used up so much stack on later subroutines that the
stack corresponded to the returned local pointer was overwritten, and
more, and then bang, the program terminated.

> Actually, returning a pointer to a local (automatic) static array is
> exactly what some implementations of standard functions like "strtok"
> do, and it works perfectly if you don't have multiple threads using
> the same function. But you should know exactly what you are doing...


Yeah, I do that alot, but I document the daylights out of the fact that
if you use it twice, you need to copy away the first return.

SteveT

Steve Litt
March 2016 featured book: Quit Joblessness: Start Your Own Business
http://www.troubleshooters.com/startbiz