Use free () without malloc ()?

4

Could it be a problem to use free() on a pointer that was not allocated with malloc() beyond the unnecessary itself?

void funcao (int par)
{

    char  *palavra;

    if(par%2 == 0)
    {
         palavra = malloc(3*sizeof(char));
         strcpy(palavra, "par");
    }

    free(palavra);  
    palavra = NULL;  
}

This is just an example, its meaning or implementation does not matter.

    
asked by anonymous 29.07.2016 / 16:12

3 answers

6

In the example shown it may cause a problem. It is called dangling pointer .

The free() is acting on the palavra variable that was not initialized. That is, in C, has a value in it, you have no idea what value this is, will vary in each execution of the generated application. It will attempt to release the memory pointed to by that address. If you get lucky you can just fail and nothing happens or you can get rid of something that was allotted and should not. Something disastrous can happen and even deallocate things completely out of the way expected, since even the size of the allocation can be erroneously considered by free() . The information is virtually random.

In C we have to be very careful. One such care is to always initialize the variable. This would cause the wrong%% to not cause problems, even though the code would not be strictly correct. The ideal is not to leave a free() free like this (I did not resist :)). It goes that someday someone changes something and it happens to be a problem even in cases where it was not initially.

    
29.07.2016 / 16:29
6

Here are some notes:

  

1 - It is a good practice to initialize pointers to NULL when declaring them, a pointer without proper initialization can point   to some invalid memory address (dangling pointer or pointer   wild);

     

2 - By default, when free() is given a NULL pointer, no action is taken, ie there is no problem in passing a   pointer NULL for free() ;

     

3 - When you allocate memory to accommodate strings, be sure to include a byte for terminator '\ 0'.

Here's a suggested improvement for your code:

void funcao( int par )
{
    char * palavra = NULL;

    if( par % 2 == 0 )
    {
        palavra = malloc( (3 + 1) * sizeof(char) );
        strcpy( palavra, "par" );
    }

    free(palavra);  
}

I hope I have helped!

    
29.07.2016 / 23:45
2

Lucas, it can cause several problems, because when the free function is to release the area of memory that in thesis should have been allocated with the function malloc and associated with a pointer, it will not be pointing to an area controlled by the compiler , so the results may be unexpected. Take care and good luck.

    
29.07.2016 / 16:18