C/Why does following code give segmentation fault ?
Expert: Narendra - 5/27/2004
QuestionThe following code after printing the output correctly gives segmentation fault. I do not why ?
# include<stdio.h>
# include<stdlib.h>
# define N 5
main()
{
char **p;
int i;
for (i=0;i<N;i++){
p[i] = " This is a message ";
}
for (i=0;i<N;i++){
printf("%s\n", p[i]);
}
}
Answerp is a pointer and you need to allocate memory to it before using. If you don't allocate memory to it, it will be pointing to some garbage. It is just like having an int variable i. Now, what is the value of this i? It can be anything, since you haven't initialized or put any value to it. The value residing in an uninitialized variable is called garbage.
Same is the case with pointer variables. They are supposed to hold a valid address. But, when you declare (or define) it, it will not contain a valid address (garbage). So, it has to be initialized to point to a valid address. This can be done in two ways. One by taking the address of another variable (which will always be valid) and using that to initialize.
Second, is to use malloc() to allocate memory, which returns a valid address.
Here below, I have rewritten your code, so that it will not crash:
# include<stdio.h>
# include<stdlib.h>
# define N 5
main()
{
char arr[5][100];
char **p = (char **)&(arr[0]);
int i;
for (i=0;i<N;i++){
p[i] = " This is a message ";
}
for (i=0;i<N;i++){
printf("%s\n", p[i]);
}
}
I have used the method one (using address of another variable) which I explained before to get valid address.
You can try out with the 2nd method.
Hope this helps......
-ssnkumar