Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

malloc

realloc

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.

like image 740
krazibiosvn Avatar asked Apr 20 '15 16:04

krazibiosvn


People also ask

How do you allocate memory to a structure?

The correct syntax is malloc(sizeof(struct st)) .

How is memory allocated using malloc?

The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form.

How do you allocate memory for structure pointer?

To allocate the memory for n number of struct person , we used, ptr = (struct person*) malloc(n * sizeof(struct person)); Then, we used the ptr pointer to access elements of person .

Can you malloc a struct?

malloc allocates sizeof(struct node) bytes, and returns a void pointer to it, which we cast to struct node *. Under some conditions malloc could fail to allocate the required space, in which case it returns the special address NULL.


1 Answers

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));
like image 162
Gopi Avatar answered Sep 20 '22 13:09

Gopi