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

The goal of my program is to read a file and display a word with maximum occurrences, as well as the number of occurrences. But I am having problems with malloc and its syntax. This is the structure that malloc refers to:

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

This section of my main section helped me find out that it was my mistake:

  printf("Pre-Allocation Test"); struct Word_setup *phrase; phrase = (struct Word_setup *) malloc(SIZE); if (phrase == NULL) {printf("Failure allocating memory"); return 0;} 

The Pre-Allocation Test seems to be printing, and then freezes. As I said, I don’t understand how to solve this problem, but I isolated it.

* If you are interested in what SIZE :

#define SIZE (sizeof(phrase))


Edit:

For those who are interested in the / OS / etc compiler version: Windows 7 64bit, GCC 4.9.2

If you would like more information about this, just let me know.

+5
source share
1 answer
 phrase = (struct Word_setup *) malloc(SIZE); 

it should be

 phrase = malloc(sizeof(struct Word_setup)); 

You have

 #define SIZE (sizeof(phrase)) 

will give you the size of the pointer, not the size of the structure. You can also use the more general memory allocation method.

 type *p = malloc(sizeof(*p)); 
+5
source

All Articles