I get a segmentation fault when I run the following program.
#include<stdio.h>
int main()
{
char *a[10] = {"hi", "hello", "how"};
int i ;
printf("%s %s %s %s %s\n",a[0],a[1],a[2],a[3],a[4]);
for (i = 0;i < 10; i++)
printf("%s\n",a[i]);
return 0;
}
output
hi hello how (null) (null)
hi
hello
how
Segmentation fault (core dumped)
I have gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1) and Linux kernel 3.16.0-34-generic.
I know that all the non initialized array entries get the value 0, so I expect a null
at the printf.
But it gives segmentation fault.
Strangely when I replaced the printf (“%s\n”,a[i])
with printf(“%s %d\n”,a[i],i)
I am able to get null
for the unfilled array entry.
In fact a space between %s
and \n
too is free from segmentation fault.
Can anybody tell me the reason behind this behavior.