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中的函数怎么会出鬼?

在此先谢过!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值