简体   繁体   中英

c++ crash on free()

i have problems with free(); all time me app crashing, without it work but some sended packet just crash. What can be wrong here? Any one can help me, thanks.

unsigned char buf[1024];
int size = 0, len;
wchar_t *wstr;
va_list args;
va_start(args, Format);

while (*Format != 0)
{

    switch (*Format)
    {
        case 'b':
            len = va_arg(args, unsigned int);
            memcpy(buf + size, va_arg(args, void*), len);
            size += len;
            break;          
        default:
            // command on unknown
            break;
    }
    Format++;   
}

va_end(args);
true_SendPacket(This, "b", size, (int)buf);
free(buf); // this line

That buffer is allocated on the stack; you only need to free heap memory, that is, memory allocated with malloc or similar functions. Stack memory is handled automatically.

Your other problem seems to be that you're casting the buffer to an int not an int array, rather than a void pointer.

free() is a C function and can be used only on memory allocated by malloc(), if your tags are true, you must try to avoid that altogether. Casting pointer to an int is UB, pointer isn't really an integral value and might be of different size than int. if you need an untyped address, you should use void*.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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