尝试 free() 结构 char * 字段时出现 SIGTRAP 异常

When trying to free() structure char * field got SIGTRAP Exception

无法弄清楚我做错了什么,在 free(packet->protocol); 函数调用时引发异常。我在 Windows 7 x64 使用 mingw64(gcc) 编译。

Program received signal SIGTRAP, Trace/breakpoint trap. 0x00000000772ef3b0 in ntdll!RtlUnhandledExceptionFilter () from C:\Windows\SYSTEM32\ntdll.dll

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

/**
 * @brief 
 * 
 */
typedef struct TCP
{
    int size;
    int crc;
    char *protocol;
} tcp_p;

/**
 * @brief Building Packet
 * 
 * @param packet 
 * @return int 
 */
int build_tcp_packet(tcp_p *packet)
{
    assert(packet != NULL);
    packet->size = 0;
    packet->crc = 0;
    packet->protocol = "TCP IP";
    return 0;
}

/**
 * @brief Free memory of Packet object
 * 
 * @param packet 
 */
void destroy_tcp_packet(tcp_p *packet)
{
    assert(packet != NULL);
    free(packet->protocol);//**Exception here**
    free(packet);
}

/**
 * @brief 
 * 
 * @return int 
 */
int main(int argc, char **argv)
{
    tcp_p *tcp_packet = malloc(sizeof(tcp_p));

    build_tcp_packet(tcp_packet);
    printf("%s\n", tcp_packet->protocol);
    destroy_tcp_packet(tcp_packet);
    getchar();

    return 0;
}

您分配给该字段的值不在堆上,它在 build_tcp_packet 函数的堆栈上。请尝试 packet->protocol = strdup("TCP IP");