0

I am learning C and I have trouble correctly using free() on char *word from my struck. The code works in its currect form but crashes if I uncomment the line in the for loop ant the end of main. How do I free it correctly?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <errno.h>

typedef struct container
{
    char *word;
    int amount;
} wordContainer;

wordContainer *SetupWordList(int *size, int *lastInit, wordContainer *listIN, bool realloc);

int main(int argc, const char *argv[])
{
    wordContainer *listWords = NULL;
    int listSize = 10;
    int listLastInit = 0;

    listWords = SetupWordList(&listSize, &listLastInit, listWords, false);

    for (int i = 0; i < listSize/2; i++)
    {
        fprintf(stdout, "Word: %s | Amount: %i\n", listWords[i].word, listWords[i].amount);
    }
    
    for (int i = 0; i < listSize/2; i++)
    {
        //free(listWords[i].word);
    }
    free(listWords);
    
    exit(EXIT_SUCCESS);
}

wordContainer *SetupWordList(int *size, int *lastInit, wordContainer *listIN, bool reallocate)
{
    if(!reallocate)
    {
        listIN = (wordContainer *)malloc((*size) * sizeof(wordContainer));
        if (listIN == NULL)
        {
            fprintf(stderr, "Could not allocate enought memory.");
            exit(EXIT_FAILURE);
        }
    }
    else
    {
        listIN = (wordContainer *)realloc(listIN, (*size) * sizeof(wordContainer));
    }
    
    for (int i = (*lastInit); i < (*size); i++)
    {
        listIN[i].word = (char *)malloc(50*sizeof(char));
        listIN[i].word = "empty";
        listIN[i].word = "cow";
        listIN[i].amount = 0;
    }

    *lastInit = *size;
    *size *= 2;

    return listIN;
}

I have honestly no idea what is the problem here, everything I could find online sugested that I am maybe using free() multiple times on the same location or that I have overwriten buffers but I don't see how this is the case here.

RobBobert
  • 35
  • 3
  • 5
    `listIN[i].word = (char *)malloc(50*sizeof(char)); listIN[i].word = "empty";` What do you think this is doing ? You've just lost your malloced pointer. Perhaps you meant `strcpy` ? – John3136 Dec 02 '22 at 10:38
  • My idea was to create a string that is up to 49 characters long, which I could then later manipulate. Did not realise that saving a string in it makes me lose that pointer. OK, thanks. That already solved my problem :) – RobBobert Dec 02 '22 at 10:43

1 Answers1

2
for (int i = (*lastInit); i < (*size); i++)
{
    listIN[i].word = (char *)malloc(50*sizeof(char));
    strcpy(listIN[i].word, "empty");
}

Solved my problem. Did not realise that "listIN[i].word = "empty";" makes me lose my mallocated pointer.

RobBobert
  • 35
  • 3