malloc和free在开发中遇到的问题

用C语言写的GPRS模块驱动代码,想在PC上测试,于是用Qt写了个界面,调用C写的驱动代码,于是碰到鬼了
static void at_send(char* context)
{

    int context_len;
    char* buf;

    context_len = strlen(context) + 5;
    qDebug("context_len: %d",context_len);
    buf = (char*)malloc(context_len);
    memset(buf,0,context_len);
    buf[0] = 'A';
    buf[1] = 'T';
    strcat(buf+2,context);
    buf[context_len+2] = '\r';
    buf[context_len+3] = '\n';
    buf[context_len+4] = '\0';
    
    qDebug() << buf;
    RS232_Tx(buf,context_len);

    qDebug() << "free buf !";
    free(buf);
    buf = NULL;
}

跑完以上这个函数有几率会出现内存错误!

查原因查到哭,还来是用固定数组来当缓冲区就没事了,不知道malloc和free是什么鬼,于是换个平台试试

static void at_send(char* context)
{
    int context_len;
    char* buf;
	
    context_len = strlen(context) + 5;
    buf = (char*)malloc(context_len);
    memset(buf,0,context_len);
    buf[0] = 'A';
    buf[1] = 'T';
    strcat(buf+2,context);
    buf[context_len+2] = '\r';
    buf[context_len+3] = '\n';
    buf[context_len+4] = '\0';
    // ͨ¹ý´®¿Ú·¢ËÍ
    //RS232_Tx(buf,context_len);
	
    free(buf);
    buf = NULL;

}
在Keil4中编译,LPC1768上运行,结果主函数都进不了,一直在启动代码里面循环!!!

有木有大神对底层熟悉的给我解释解释,malloc和free这两个标C中的函数怎么会出鬼?

在此先谢过!

你可能感兴趣的:(C/C++)