Click to See Complete Forum and Search --> : printf and strlen gives a segmentation fault


kam
02-23-2004, 02:32 AM
#include <string.h>
#include <stdio.h>

int main() {
char buffer[] = "blah";
printf(strlen(buffer));
}#include <string.h>
#include <stdio.h>

int main() {
printf(strlen("blah"));
}#include <string.h>
#include <stdio.h>

int main() {
int x = strlen("blah");
printf(x);
}
All of these give a segmentation fault. Why? This does not segfault:#include <string.h>
#include <stdio.h>

int main() {
int x = strlen("blah");
}

PolteRGeisT
02-23-2004, 02:42 AM
when using printf(), do it this way



printf("%d", strlen(buffer));

printf("%d", x);


I'm too tired to explain right now, but someone most definately will within the next 12 hours.

nabis
02-23-2004, 04:05 AM
within next 3 hours exactly.
Yeah, kam, you are omitting the format specifier to printf, so it just dumps core.

kam
02-23-2004, 07:42 PM
I think I understand why. If I omit "%d" printf treats the return of strlen() as a char*, and prints until it gets to NULL and so goes over the end, hence the segfault. Thanks for the help.

bwkaz
02-23-2004, 08:12 PM
Not really, but sort of -- when strlen() returns an integer, printf() interprets that as a pointer to a character (the start of a string). The integer that strlen() returns is not actually a valid pointer (it doesn't point at anything), so when printf tries to read in the format string (through the invalid pointer), it segfaults.

If strlen() returned 0 for example, then it would be the exact same as trying to run this code:

printf(NULL); which will make printf indirect through a NULL pointer when trying to find its format string.

So yes, it does interpret the return value of strlen() as a char pointer like you said, but the problem isn't that it's looking for a null character ('\0' -- which is not necessarily NULL: since the type of NULL is a void *, while the type of '\0' is char, that means that even though they have the exact same value, their sizes are different), the problem is that the return value of strlen when cast to a pointer is not a valid pointer.

I bet you'd get a bunch of warnings (or at least one) if you compiled with -Wall...

kam
02-23-2004, 11:13 PM
Okay, thanks bwkaz. That's very clear.