Alexios Naval
Alexios Naval

Reputation: 93

How do I free() a non-heap object?

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

int** intptrArray;
char word[50];

I'm trying to use free() on both the array and word after I allocate them using malloc in the function that comes after this. free(intptrArray) seems to work just fine but everytime I try free(word), free(*word), or free(&word), I get errors - most common is "attempt to free non-heap object".

How can I resolve this? TIA!

Upvotes: 3

Views: 9183

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

'm trying to use free() on both the array and word after I allocate them using malloc in the function that comes after this.

It seems you do not understand how functions accept arguments that have an array type.

I can guess that what you are doing looks similar to the following program.

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

void f( char word[] )
{
    word = malloc( 50 * sizeof( char ) );
    strcpy( word, "Hello World!" );
    
    puts( word );
}

int main(void) 
{
    char word[50] = "Bye!";

    f( word );
    
    puts( word );
    
    return 0;
}

The program output

Hello World!
Bye!

As you can see the array word was not changed. Within the function you did not change the array word declared in main. When you passed the array to the function f it is implicitly converted to pointer of the type char *. This pointer (parameter) is a local variable of the function. So you changed the local variable. The array itself declared in main was neither changed nor reallocated. It has the automatic storage duration and it is the compiler that will free the declared array after the function main will finish its execution.

On the other hand, the allocated memory pointed to by the parameter word of the function f indeed must be freed. Otherwise there will be a memory leak. It can be done within the function for example like

void f( char word[] )
{
    word = malloc( 50 * sizeof( char ) );
    strcpy( word, "Hello World!" );
    
    puts( word );

    free( word );
}

Upvotes: 0

dbush
dbush

Reputation: 223719

How do you free a non-heap object? You don't.

The purpose of free is to make allocated heap memory available for other uses by the program. So you should only pass to free pointer values that were returned from malloc / calloc / realloc.

Upvotes: 7

Related Questions