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.
The correct syntax is malloc(sizeof(struct st)) .
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.
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 .
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With