c语言,问题1:传入参数私自变化?问题2:调用函数后程序无故死掉? 原因分析

1:c语言,在被调用函数里并未改变传入参数,参数却变化了的原因分析

2:c语言,调用函数后程序无故死掉原因分析

1:我在函数1中调用函数2,由函数1向函数2传入(uint32_t a,uint32_t b),在函数里并未写改变传入的参数a的语句,结果参数a在操作时竟然不是传入的值,后来找到原因是传入参数a,b,在函数2中操作b时将a值覆盖了,造成操作a时并不是传入的值,那么操作b时怎么会将a覆盖呢,原因是我在函数1中定义a,b

int fun1()
{
    uint32_t a;
    uint16_t b;
    ...
    fun2(&a,&b...)
}
int fun2(uint32_t *m,uint32_t *n);

在函数1中定义的b为uint16_t,而传入函数2,函数2把b当成uint32_t数据,当操作b时就会覆盖a地址里的东西,在函数1中,a先入栈,然后b入栈,


当b的地址传入函数2时,函数2把b当成32位的数据操作,就会操作a的前16位,而导致传入参数a数据出错。


我们以为我们没有改变传入参数,实际上由于操作越界就是被调用函数改变了传入参数。

2:那么问题2也是相同的问题,如果函数1的第一个参数在操作时越界,那么调用函数1的函数的压栈返回信息将被破坏,调用函数1的函数将不能返回,最后导致程序崩溃。

我的出错实例:f_read函数传参传错了,导致越界

p_inf *readPicInf(char *pfilepath)
{    
    FIL fileDescriptor;   
    uint16_t readByteResult;
    char fOptResult;
    
    p_inf *infReturn;
    
    fOptResult = f_open(&fileDescriptor, (const TCHAR*)pfilepath, FA_READ);
    if ((fOptResult != FR_OK) || (fileDescriptor.obj.objsize > BMPMEMORYSIZE)) 	return NULL;
  
    infReturn = (p_inf *)malloc(sizeof(p_inf));
    if (infReturn == NULL) return NULL;
    
    infReturn->pfilestring = (char *)malloc(fileDescriptor.obj.objsize);
    if (infReturn->pfilestring == NULL) return NULL;
 
    fOptResult = f_read(&fileDescriptor,infReturn->pfilestring,fileDescriptor.obj.objsize, (UINT *)&readByteResult);
    if (fOptResult != FR_OK) return NULL;

    infReturn->pfilesize = fileDescriptor.obj.objsize;
    
    f_close(&fileDescriptor);
    return infReturn;
}
FRESULT f_read (
    FIL *fp,    /* Pointer to the file object */
    void *buff, /* Pointer to data buffer */
    UINT btr,   /* Number of bytes to read */
    UINT *br    /* Pointer to number of bytes read */
)
{
    FRESULT res;
    FATFS *fs;
    DWORD clst, sect;
    FSIZE_t remain;
    UINT rcnt, cc, csect;
    BYTE *rbuff = (BYTE *)buff;
    *br = 0;    /* Clear read byte counter */
    res = validate(&fp->obj, &fs);              /* Check validity of the file object */
    .....
}

                
  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值