您的位置:首页 > 编程语言 > C语言/C++

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

2017-10-13 09:27 477 查看
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 */
.....
}


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐