krazibiosvn
krazibiosvn

Reputation: 85

How do you use malloc to allocate memory for a structure?

The goal of my program is to read a file, and output the word with the max appearances, as well as the number of appearances. But I'm having issues with malloc and the syntax of it. This is the structure which malloc refers to:

struct Word_setup {
    char word[max_length];
    int count;
};

This section of my main helped me find out that this was my error:

    printf("Pre-Allocation Test");

    struct Word_setup *phrase;

    phrase = (struct Word_setup *) malloc(SIZE);

    if (phrase == NULL)
        {printf("Failure allocating memory"); return 0;}

It only seems to print out, Pre-Allocation Test, and then freezes. As I said before, I'm unclear how to fix this issue, but I've isolated it.

*Incase you're wondering what SIZE is:

#define SIZE (sizeof(phrase))


Edit:

For those curious about compiler version/OS/etc.: Windows 7 64bit, GCC 4.9.2

If you would like any more information on that just let me know.

Upvotes: 5

Views: 667

Answers (1)

Gopi
Gopi

Reputation: 19864

phrase = (struct Word_setup *) malloc(SIZE);

should be

phrase =  malloc(sizeof(struct Word_setup));

What you have is

#define SIZE (sizeof(phrase)) 

will give you size of pointer not size of structure. You can also use a more generic method of allocating memory

type *p = malloc(sizeof(*p));

Upvotes: 5

Related Questions