Reputation: 697
I'm new to C, and I'm trying to write simple schedule program. I have rooms and want to fill them with events.
static void create_dummy_data()
{
#define max_entries 5
struct event
{
char *event_name;
int duration_min; // duration in minutes
};
struct room
{
char *room_name;
struct event *events[10];
};
int i = 0;
char *names[] = {"Room1", "Room2", "Room3", "Room4", "Room5", "Room6"};
struct room *rooms[max_entries];
for ( i = 0; i < max_entries ; i++)
{
rooms[i]->room_name = names[i]; // The problem is here
}
}
I'm getting error "8263 segmentation fault (core dumped)"
Upvotes: 1
Views: 76
Reputation: 11821
When you declare struct room *rooms[max_entries];
you will have in the data segment an array of max_entries
pointers that are initialized to NULL
.
As you do not allocate memory for your room, it means that when you write rooms[i]->room_name
you will have essentially done the same as NULL->room_name
. The memory protection mechanism of you system detects that you want to access a memory portion that is not allowed and signals it to you with a segmentation fault.
you have to add:
rooms[i] = malloc(sizeof (struct room));
if(!rooms[i]) exit(EXIT_FAILURE); // example error handling, can be different
to your loop.
BTW: it is usage in C to define macros in all caps so that it is immediately visible that it is a macro. You should therefore use
#define MAX_ENTRIES 5
instead.
Upvotes: 3