2

My program compiles but I am not working with pointers and realloc correctly. I have tried looking at other examples but I can't seem to translate it to my own program. The point of the program is to read in words from a file and increment the count if they appear more than once. Once the array of structs goes over my base (5), I want to realloc space, copy the array over and then add the next word.

Any help would be greatly appreciated!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BASE 5
#define MAX 50

typedef char *string;

 struct wordCount 
 {
 string word; 
 unsigned int count;
  }; 

 int main (void)
 {  
unsigned int i; 
unsigned int incremented; 
unsigned int j; 
char temp [40];  
struct wordCount wordArray[BASE]; 
struct wordCount *holder;  
FILE *infile;   

j = 0; 
infile = fopen("input.txt","r");
while (fscanf(infile, "%s", temp) == 1) { 
    incremented = 0; 
    for (i = 0; i < j; i++){
        if(strcmp(temp,wordArray[i].word) == 0){
            wordArray[i].count++;
            incremented++; 
        } 
     }
     if (incremented == 0){
        if (j<BASE){     
            wordArray[j].word = (char *)malloc((strlen(temp)+1) * 
                               sizeof(char));
            strcpy(wordArray[j].word,temp); 
            wordArray[j].count = 1; 
            j++;  
        } else {
          holder = realloc(wordArray, sizeof(wordArray) +1);
          *wordArray = *holder;
          wordArray[j].word = (char *)malloc((strlen(temp)+1) * sizeof(char));
          strcpy(wordArray[j].word,temp); 
          wordArray[j].count = 1; 
          j++; 
        }
     }
}

fclose(infile);

/* bring in next file*/
/*delete du plicates */ 
/*sort*/ 

for (i = 0; i < j; i++) {
    printf("%s ", wordArray[i].word);
    printf("%d\n", wordArray[i].count); 
}
/* and when done:*/ 
   for(i = 0; i < j; i++){
      free(wordArray[i].word);
}

return 0; 
 }

1 Answer 1

3

Here's the most obvious place you're going wrong:

holder = realloc(wordArray, sizeof(wordArray) +1);

Note this line from the man page of realloc():

void *realloc(void *ptr, size_t size);
...
Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc().

Your wordArray is a statically allocated array, it was not dynamically allocated via malloc() or friends.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.