Albermonte
Albermonte

Reputation: 31

Freeing memory for struct.name (debug error: HEAP CORRUPTION DETECTED)

I'm creating dynamic arrays with the length of a name inputed by the user, but when I want to free() the memory allocated with malloc() it's giving me a "Debug error"

typedef struct
{
    char *nombre;
    float nota;
} tficha;

tficha leeFicha() 
{
    char nombreTam[100]; 
    int tamNombre;      
    tficha ficha;       
    scanf("%s",nombreTam); 
    tamNombre=strlen(nombreTam); 
    ficha.nombre=(char *)malloc(tamNombre*sizeof(char)); 
    strcpy(ficha.nombre,nombreTam); 
    free(ficha.nombre); // Here is giving me a Debug Error (HEAP CORRUPTION DETECTED: after Normal block (#166) at 0x0065C450. CRT detected that the application wrote to memory after end of heap buffer.)
    return ficha;       
}

How can I free ficha.nombre without errors?

Upvotes: 0

Views: 745

Answers (1)

abligh
abligh

Reputation: 25139

You are correctly finding the length of the string:

tamNombre=strlen(nombreTam); 

but when you allocated the memory:

ficha.nombre=(char *)malloc(tamNombre*sizeof(char)); 

you allocate only enough memory for the characters of the string, and not the terminating NUL. You want:

ficha.nombre=(char *)malloc(tamNombre*sizeof(char)+1); 

But as char is guaranteed by the C standard to be of size 1, you can write:

ficha.nombre=(char *)malloc(tamNombre+1); 

And as you don't need to cast the return of malloc(), the simplest is:

ficha.nombre=malloc(tamNombre+1); 

Without this change, the strcpy is writing beyond the end of the allocated memory, which is probably what is causing your problem.

However, it also seems peculiar that you are doing:

free(ficha.nombre);

within this function anyway. That guarantees that the ficha struct has a pointer to deallocated memory - i.e. you effectively 'forget' the number as soon as it is entered. Rather you should be free()ing ficha.nombre when you have done with the ficha struct - presumably the caller needs the value after all.

Upvotes: 2

Related Questions