Scoping question in C
Henry Spencer
henry-lqW1N6Cllo0sV2N9l4h3zg at public.gmane.org
Mon Jun 13 20:36:28 UTC 2005
On Mon, 13 Jun 2005 billt-lxSQFCZeNF4 at public.gmane.org wrote:
> > If you don't know how long it is, there's really not much you can usefully
> > do with it. You *have* to have either NUL termination or a known length...
>
> It is possible to count the number of characters until a NUL is found...
*If* you're confident that there is a NUL at the end. If there isn't one,
it's quite possible for unkind things (e.g. a segmentation-fault trap) to
occur before you happen across a NUL in memory.
For that matter, even if you do reach an accidental NUL before getting a
trap etc., you could end up with a "string" that happens to overlap the
buffer you're going to copy it into... in which case strcpy() may well
infinite-loop or otherwise misbehave.
I repeat: you *have* to have either NUL termination or a known length.
Somehow you have to know where the sequence of characters ends!
> x=0;
> while ( string[x] != 0 ) { x++; }
> y= malloc(sizeof(char)*(x+1) );
> stcpy (string, y);
> Note there is no guarentee the program is correct or works.
It's not and doesn't. :-) Should be something like:
y = malloc(strlen(string) + 1);
assert(y != NULL);
strcpy(y, string);
Using strlen() is easier and possibly faster than doing it yourself.
sizeof(char) is guaranteed to be 1 and hence arguably doesn't need
explicit mention. A more graceful out-of-memory recovery strategy would
be better than assert(), but *something* needs to check that malloc()
succeeded. And strcpy() copies from second operand to first, not the
other way.
Henry Spencer
henry-lqW1N6Cllo0sV2N9l4h3zg at public.gmane.org
--
The Toronto Linux Users Group. Meetings: http://tlug.ss.org
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://tlug.ss.org/subscribe.shtml
More information about the Legacy
mailing list