1

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)"

dust_bg
  • 405
  • 4
  • 15
  • 5
    `struct room *rooms[max_entries];` where do you allocate memory for those rooms? – Blaze Jul 11 '19 at 09:08
  • You have an array of pointers (a couple of them actually, considering the `events` member of the `room` structure), but where do these pointers actually point? Perhaps you don't even need pointers, but could have an array of structure objects instead? – Some programmer dude Jul 11 '19 at 09:09
  • refer to : [What is a segmentation fault?](https://stackoverflow.com/questions/2346806/what-is-a-segmentation-fault) – Sander De Dycker Jul 11 '19 at 09:12
  • You need to read about dynamic memory allocation. – klutt Jul 11 '19 at 09:25

1 Answers1

3

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.

Patrick Schlüter
  • 11,394
  • 1
  • 43
  • 48