Groovy hepcat (e-mail address removed) was jivin' on 11 Jan 2007 06:41:51
-0800 in comp.lang.c.
segmentation fault ... SIGSEGV's a cool scene! Dig it!
What is wrong with the reverse function, gives a segmentatiion
violation. I think it is relates to data alignment.(4 bytes ...).
int main(void)
{
char *s="abcdexgh";
reverse(s);
printf("%s",s);
Undefined behaviour. Can you guess why, hmm? Well, I'll tell you.
Like all variadic functions, printf() needs a prototype, otherwise any
use of it causes undefined behaviour, according to the standard. Also,
since you have not declared the return type of printf(), the (C90)
compiler assumes it returns an int. In this case that just happens to
be correct. By sheer luck you have avoided more undefined behaviour.
But it won't always be the case. (See below.) (A C99 compiler will at
least diagnose this, and likely refuse to compile it.)
And just think; you could've avoided this problem simply by
including stdio.h.
}
void reverse( char *s)
{
char *q,*p;
int j;
char t;
j=strlen(s);
Undefined behaviour. Can you guess why, hmm? Well, I'll tell you.
Since there is no declaration of strlen() in scope, the (C90) compiler
thinks it returns an int. (A C99 compiler will at least diagnose this,
and likely refuse to compile it.) When strlen() actually returns a
size_t, an implementation defined unsigned integer type, the compiler
attempts to interpret that as a signed int. Different types may be
returned in different places. And they may have different sizes. But
in either case, they have different representations.
And just think; you could've avoided this problem simply by
including string.h.
--
Dig the even newer still, yet more improved, sig!
http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?