segmentation fault

R

ramu

Hi,
While am trying to run this code am getting segmentation fault.
What's wrong with this code?
Here am trying to assign a value to the variable b.

#define SIZE 10

struct y {
int a;
struct x {
int b;
} *c[SIZE];
} d;


main()
{

d.c[SIZE] = malloc(10 * sizeof(struct x));
d.c[0]->b=10;
printf("%d",d.c[0]->b);
}

Regards
 
C

Chris Dollin

ramu said:
Hi,
While am trying to run this code am getting segmentation fault.
What's wrong with this code?
Here am trying to assign a value to the variable b.

#define SIZE 10

struct y {
int a;
struct x {
int b;
} *c[SIZE];
} d;

[Horrid names. I assume they're just for illustration.]
main()
{

d.c[SIZE] = malloc(10 * sizeof(struct x));

BOOM. `d.c` has only SIZE elements, indexed from 0 to
`SIZE - 1`. So your code has already broken. And you
didn't #include stdlib.h, so your use of `malloc` is
broken too. (Didn't your compiler complain about that?)

It's quite possible that this didn't cause your problem,
however.
d.c[0]->b=10;

You haven't assigned to `d.c[0]`. Since `d` is static,
its elements are initialised to zero. So `d.c[0]` is
a null pointer. You've tried to assign to a field of
a structure the null pointer doesn't point to.

BOOM. Very likely the point at which you get your
segfault.
 
M

mark_bluemel

ramu said:
Hi,
While am trying to run this code am getting segmentation fault.
What's wrong with this code?
Here am trying to assign a value to the variable b.

#define SIZE 10

struct y {
int a;
struct x {
int b;
} *c[SIZE];
} d;


main()
{

d.c[SIZE] = malloc(10 * sizeof(struct x));

I think you are trying to dynamically allocate the array of SIZE
pointers to struct x items here. It won't work.

Depending on what you are trying to achieve, you could do this :-

int i;
for (i = 0;i < SIZE;i++) {
d.c = malloc(sizeof(struct x));
} /* error handling is missing */

still remembering that you can only access from d.c[0] to d.c[SIZE -
1], so you could do

d.c[10]->b = 42;

or you could change the structure declaration

struct y {
int a;
struct x {
int b;
} *c;
} d;
....
d.c = malloc(sizeof(struct x) * SIZE);
/* or d.c = calloc(SIZE, sizeof(struct x));
* again error handling is missing
*/
d.c[SIZE - 1].b = 42;

I'll now stand back and let others find the holes in what I've
suggested :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top