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

时间:2018-10-23 22:03:51

标签: c malloc free

无法弄清楚我在做什么,在free(packet->protocol);函数调用上会引发异常。我在Windows 7 x64操作系统上使用mingw64(gcc)进行编译。

  

程序收到信号SIGTRAP,跟踪/断点陷阱。   ntdll中的0x00000000772ef3b0!RtlUnhandledExceptionFilter()来自   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;
}

1 个答案:

答案 0 :(得分:2)

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