1
votes

free() does not seem to de-allocate memory when I compile. I have previously allocated using malloc() and I tested it to ensure the pointer is not null.

These are the errors I get when I compile my code:

malloc: * error for object 0x7ffee53e1aa4: pointer being freed was not allocated malloc: * set a breakpoint in malloc_error_break to debug

void math(int array[], int length, int* sum, int* mult);

int main(void)
{
    int sum = 0;
    int mult = 1 ;
    int a[] = {1, 33, 12, 2, 9, 2};

    int* sump = (int*) malloc(1*sizeof(int));

    if(sump == NULL){
        printf("sump is null");
    }

    int* multp = (int*) malloc(1*sizeof(int));

    if(multp == NULL){
        printf("multp is null");
    }

    sump = ∑
    multp = &mult;

    math(a, 6, sump, multp);

   if(sump != NULL){
       free(sump);
   }
if(multp != NULL){
       free(multp);
   }

    printf("sum: %d mult: %d\n", sum, mult);


    return 0;
}

void math(int array[], int length, int* sump, int* multp)
{
    int i;
    int sum = 1; 
    int mult = 1;

    for(i=0; i<length;++i){
        sum += array[i];
        mult *= array[i];

    }

    printf("%d %d\n", sum, mult);

    *multp = mult;
    *sump = sum;   

}
1
You should actually abort the program in the case of the NULL tests being trueM.M
sump = &sum; losses the allocated value. What are you trying to do?Mad Physicist
sump = &sum; means that the pointer sump now points at the automatic variable sum, so you get an error when you try to free it. free(sump); means to free the memory which sump is pointing to.M.M
The code should be *sump = sum; | *multp = mult; .rcgldr
That's a run-time error, not a compile-time error.Keith Thompson

1 Answers

0
votes
int* sump = (int*) malloc(1*sizeof(int));

sump now points to an anonymous object created by malloc.

sump = &sum;

Now sump points to the object sum that you defined earlier. The allocated object is lost.

if(sump != NULL){
    free(sump);
}

The NULL check is unnecessary, since free(NULL) is legal and does nothing. But since sump no longer points to an allocated object, free(sump) has undefined behavior. (You're lucky that your run-time system was able to diagnose it for you.)

The error message was generated at run time, not at compile time.

And you're missing the required #include directives at the top of your code:

#include <stdio.h>
#include <stdlib.h>