设置变量的值时无法释放内存

当我尝试释放内存时,出现内存分配错误,但是当我尝试释放内存而不定义名称时,它可以正常工作。

输入项

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

void main()
{
    char* name = malloc(5 * sizeof(char));
    name = "Jeff";

    printf("%s",name);

    free(name); 
}

输出量

0 [main] memallocation 1434 cygwin_exception::open_stackdumpfile: Dumping stack trace to memallocation.exe.stackdump
评论
  • pdolor
    pdolor 回复

    您收到错误是因为您没有释放自己的想法。

    执行此操作时:

    name = "Jeff";
    

    You overwrite the memory address returned from malloc with the address of the string constant "Jeff". So when you call free you're passing it the address of the string constant.

    The proper way to copy a string is to use the strcpy function:

    strcpy(name, "Jeff");
    

    This copies the string into the memory buffer returned from malloc. Then you can safely call free on it.