Hi I have been working on a C assignment, and I have been stuck on one portion of the assignment for a few days now. My problem comes with some memory allocation.
I have the following struct definitions.
struct word_count_struct {
char *word;
int count;
};
struct bag_struct {
struct word_count_struct *bag;
int bag_size;
int total_words;
};
In this function I have to;
void add_word( struct bag_struct *bow, char *word );
Define a word_count_struct pointer, and use the new_word_count function to make it point to a new word_count structure for the provided word. (The new_word_count function is another function in the assignment, I will show it below)
I need to make the bow bigger to accommodate the new word_count struct. Using realloc. By setting the bow pointer to be equal to the value returned by realloc and also use it as the first argument. Then set the amount of memory in the realloc function to be the "sizeof" a word_count_structure multiplied by the bag->size (after adding 1 to it).
Use memcpy to copy the contents of the word_count_struct pointer's data into bow (at the last index). Watch out for the order of the pointers in the memcpy command (the destination comes before the source).
Currently, I am having problems using realloc. I seem to be getting a segmentation fault.
My code thus far is.
void add_word( struct bag_struct *bow, char *word ){
struct word_count_struct *aPtr;
aPtr = new_word_count(word);
bow = realloc( bow, (sizeof(aPtr) * bow->bag_size) + 1);
}
My code will run with no errors, however I will be automatically hit with a segmentation fault. If I comment out the realloc line, there will be no segmentation fault, however it is part of the assignment instruction so I have no choice.
I am also having trouble understanding what it means to put the memory contents of the word_count_struct pointer's data into the bow (at the last index). Particularly where it says the last index.
Here is the new_word_count I said I would include above. ( I don't know if this would help ).
struct word_count_struct *new_word_count( char *word ){
struct word_count_struct *new;
new = malloc(sizeof(struct word_count_struct));
new -> count = 1;
new -> word = word;
return new;
}
If you have any tips or ideas on what I could do to solve this it would be very appreciated.