0

I have this function which is using calloc to create an array of structure proposition. Whenever I try to free the resulting array from another fuction, it crashes.

proposition* get_matching_propositions(char *pcde, proposition *propositions, int *match_count)
{    
    proposition *matches;
    int         count       = get_count_from_stream(ptf_proposition, sizeof(proposition)),
                cptr_match  = 0;

    for (int i = 0; i < count; i++)
    {
        if (strcmp(propositions[i].cde, pcde) == NULL)
        {
            cptr_match++;
        }
    }

    matches = (proposition*) calloc (cptr_match, sizeof(propositions));
    assert(matches != NULL);

    cptr_match = 0;
    for (int i = 0; i < count; i++)
    {
        if (strcmp(propositions[i].cde, pcde) == NULL)
        {
            matches[cptr_match] = propositions[i];
            cptr_match++;
        }
    }
    *match_count = cptr_match;
    return matches;
}

Inside some other function I have:

proposition *matches =
    get_matching_propositions(current_question.cde, propositions, &match_count);
free(matches);

Then the program crashes with this message :
Process returned -1073740940 (0xC0000374) execution time : 1.370 s.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • 1
    Questions seeking debugging help should generally provide a [mre] of the problem, which includes a function `main` and all `#include` directives. This allows other people to easily test your program, by simply using copy&paste. – Andreas Wenzel Jun 12 '22 at 17:24
  • 1
    `sizeof(propositions)` is the size of a pointer – stark Jun 12 '22 at 17:28
  • 1
    `sizeof(propositions)` is not the size of the structure, it's the size of a pointer. So you either want `sizeof(*propositions)` or `sizeof(proposition)`, or even `sizeof(*matches)`. The difference between what you have and `sizeof(propositions)` is just the `s` at the end, which is a good indiction that you need to adopt a better naming convention to avoid typos like this in the future. – user3386109 Jun 12 '22 at 17:29

0 Answers0