dimanche 28 juin 2015

"Segmentation fault" when accesing dynamically allocated struct members

I have started to work on a program which implements a structure called "PhoneBook" having two members: "length" and "allocatedSpace", both of type "unsigned int". The structure is dynamically allocated. The two members of the structure are assigned in an external function called "InitializePhoneBook". Now, when I try to print the values of the two members of the structure inside the "main" function I get a "Segmentation fault" error.

PhoneBook.h

#ifndef PHONEBOOK_H
#define PHONEBOOK_H

struct PhoneBook
{   
    unsigned int length;
    unsigned int allocatedSpace;
};

void InitializePhoneBook(struct PhoneBook *phoneBook);
void ClearPhoneBook(struct PhoneBook *phoneBook);

#endif

PhoneBook.c

#include <stdlib.h>

#include "PhoneBook.h"

void InitializePhoneBook(struct PhoneBook *phoneBook)
{
    phoneBook = malloc(sizeof(struct PhoneBook) * 1);

    phoneBook->length = 0;
    phoneBook->allocatedSpace = 1000;
}

void ClearPhoneBook(struct PhoneBook *phoneBook)
{
    free(phoneBook);
}

main.c

#include <stdio.h>
#include <stdlib.h>

#include "PhoneBook.h"

int main(void)
{
    struct PhoneBook *phoneBook;

    InitializePhoneBook(phoneBook);

    printf("%d %d\n", phoneBook->length, phoneBook->allocatedSpace);

    ClearPhoneBook(phoneBook);

    return 0;
} 

Running "./a.out" with "gdb" I get:

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400621 in main () at ./main.c:12
12      printf("%u %u\n", phoneBook->length, phoneBook->allocatedSpace);

Aucun commentaire:

Enregistrer un commentaire