statements following strcpy cause parse error
Rupert Wood
me@rupey.net
Fri Feb 8 01:28:00 GMT 2002
Bjorn Rohde Jensen wrote:
> > prog # 2 which throws a parse error before 'char' (meaning
> > the strcpy
> > line??)
> >
> > #include <string.h>
> > int main()
> > {
> > char filename[256];
> > strcpy (filename, "/etc/bogus.conf\0");
> > char unused[256];
> > return 0;
> > }
>
> In prog#2 you declare a variable in the function body, that is a C++
> feature, so prog#2 is legal C++ but illegal C. You have to move the
> declaration to the top of main to make it legal C.
Yes; alternately, you can introduce a new scope for the new variable:
#include <string.h>
int main()
{
char filename[256];
strcpy (filename, "/etc/bogus.conf\0");
{
char unused[256];
}
return 0;
}
because you are also allowed to introduce new variables at the top of
new scopes (which applies equally to if/for/while scopes, etc.). I've
heard apocryphal stories about compilers mis-optimising this
construction - but you're safe with GCC :-)
You also don't need the \0 at the end of the string unless you
deliberaltely want two - you automatically get nuls at the end of string
constants. (And as a strcpy source, you *don't* need two.) Further style
- you may want to use strncpy instead:
char filename[256];
strncpy (filename, "/etc/bogus.conf\0", 256);
or maybe
strncpy (filename, "/etc/bogus.conf\0", sizeof(filename));
just to get into the habit of using it if nothing else; this helps
prevent buffer-overflow security holes.
(You may even want avoid assuming that characters are size 1
strncpy (filename, "/etc/bogus.conf\0",
sizeof(filename)/sizeof(filename[0]));
for unicode, etc. - but then you'd need to change function and
string-constant style, etc.)
Rup.
More information about the Gcc-help
mailing list