Why this C program is crashing?

Hi,

Why I am getting 'SIGSEGV' in the following code?

char* p="abcde";
printf("%s", 3[p]);     // Segmentation Fault (core dump)

Kindly help me to understand what exactly makes the program to crash or the reason for the crashing.

Don't you mean p[3] instead of 3[p] ? Also, p[3] will give you a single char , whereas you'll need a char * for the printf , so better use p+3 instead.

Kindly help me understand what you were even trying to do here, I'm not sure. It's crashing because you're giving %s something that's not a string.

char* p="abcde";
printf("%c", 3[p]);     

should work fine. I believe that this is just a test of the fact that p[3] and 3[p] are supposed to behave the same way. He probably going to enter the obfuscated C contest or something like that. :rolleyes:

When you ask UNIX to reference memory you do not own, the OS generates a signal, SIGSEGV. This triggers a crash dump.

%s in printf assumes that what you give it is an address in memory that points to a nul-terminated array of characters. IT blindly goes ahead and tries to access a valid string. Instead it tried to access some unknown address outside of process memory, so it crashed.

1 Like

Hehehe. I was thinking the same thing.

A bit more info for those interested in this "feature": Question 6.11

And ... it gets worse:

$ cat acomm.c
#include <stdio.h>

int
main(int argc, char **argv) {
	char *s = "char *s";
	char *a[1][2][3];
	a[0][1][2] = s;

	(void) printf("%s\n", a[0][1][2]);
	(void) printf("%s\n", 2[1[0[a]]]);
	(void) printf("%s\n", 2[0[a][1]]);
	(void) printf("%s\n", 1[a[0]][2]);
	/* etc */

	return 0;
}


$ cc -Wall -pedantic acomm.c 
$ ./a.out 
char *s
char *s
char *s
char *s
$ cc --version
i686-apple-darwin8-gcc-4.0.1 (GCC) 4.0.1 (Apple Computer, Inc. build 5370)
Copyright (C) 2005 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Regards,
Alister

1 Like

Awesome !! Thanks a ton :slight_smile:

Hi,

printf("%s",&3[p]);

3[p] is a character whereas %s needs the address of a character buffer.

Thanks,
Gaurav.