简体   繁体   English

释放struct.name的内存(调试错误:HEAP CORRUPTION DETECTED)

[英]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" 我正在创建具有用户输入名称长度的动态数组,但是当我想要free()malloc()分配的内存时,它给了我一个“调试错误”

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? 如何免费释放ficha.nombre

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. 您只能为字符串的字符分配足够的内存,而不为结尾的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: 但是由于C标准保证char的大小为1,因此您可以这样写:

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

And as you don't need to cast the return of malloc() , the simplest is: 而且,由于您无需转换malloc()的返回值 ,所以最简单的方法是:

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. 没有此更改, strcpy的写入将超出分配的内存末尾,这可能是导致您出现问题的原因。

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 - ie you effectively 'forget' the number as soon as it is entered. 这样可以保证ficha struct具有指向已释放内存的指针-即,输入数字后,您就可以有效地“忘记”该数字。 Rather you should be free() ing ficha.nombre when you have done with the ficha struct - presumably the caller needs the value after all. 相反,在处理ficha.nombre ficha struct应该对ficha.nombre进行free()操作-可能是调用者毕竟需要该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM