You are here:

C/Why does following code give segmentation fault ?

Advertisement


Question
The 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]);
  }

}


Answer
p 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

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.