Segmentation fault in small C program
I'm writing a C program. It compiles fine but when I try to run the binary I get a seg fault. I ran gdb but I got a pr开发者_JS百科oblem at the following line
*total = a;
The problem is right at the beginning of the code. Here it is:
main(){
int a[] = {1,1,1,0,0,0,0};
int **total; //array of int arrays
*total = a; //i.e. set total's first array to be a.
I'm new to C and pointers. Any help would be appreciated.
total
points to a pointer p
which points to an int. By assigning to *total
, you're assigning to p
. But total
hasn't been initialized, so you're assigning a value into a random location. You need to initialize total
-- for example
int * p;
int** total = &p;
You're getting the segfault because total
is uninitialized and so *total
points to a random space in memory. You want to allocate space for total:
total = malloc(sizeof (int *) * NUM_ARRAYS);
Alternatively, you can ignore the pointers and make total an array:
int *total[NUM_ARRAYS];
Demote the arrays total
points to to pointers to their first elements, and you're good to use it like this:
total[0] = a;
If you think of pointers as holding the addresses of variables, things might be clearer.
The code need not always give you a segmentation fault. When you declare
int *p
sizeof(int*) bits are allocated to p.(This is 32 in the case of a 32 bit compiler.) p is supposed to point to whatever is stored in the allocated space. Now as you haven't initialized this value. So this could contain some random value. When you do
*p=10 //say
you are essentially trying to access the location. If the location comes outside the memory accessible to your process, you get a segmentation fault. If the location happens to be accessible, this will "corrupt" the location and your program behaves mysteriously.
You haven't allocated any memory to total
. With total
uninitialized, assigning to *total
is invoking undefined behaviour. Luckily, you're getting a segfault. As long as you allocate memory to total
(or just use an array of pointers, as I'm guessing that's your intent), it'll work just fine.
total
points to something. You haven't specified what it points to (which is supposed to be another pointer), and yet you're trying to write something to that location, hence the error.
精彩评论