Search code examples
cmallocfree

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


Can't figure out what I'm doing wrong, exception fires on free(packet->protocol); function call. Im on Windows 7 x64 compiling with 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;
}

Solution

  • The value you assign to that field isn't on the heap, it's on the stack of the build_tcp_packet function. Try packet->protocol = strdup("TCP IP"); instead.