:: Re: [DNG] Making sense of C pointer…
Góra strony
Delete this message
Reply to this message
Autor: KatolaZ
Data:  
Dla: Steve Litt
CC: dng
Temat: Re: [DNG] Making sense of C pointer syntax.
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...

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

My2Cents

KatolaZ

--
[ Enzo Nicosia aka KatolaZ --- GLUG Catania -- Freaknet Medialab ]
[ me [at] katolaz.homeunix.net -- http://katolaz.homeunix.net -- ]
[ GNU/Linux User:#325780/ICQ UIN: #258332181/GPG key ID 0B5F062F ]
[ Fingerprint: 8E59 D6AA 445E FDB4 A153 3D5A 5F20 B3AE 0B5F 062F ]