强制类型转换失败,什么原因列

C语言 码拜 8年前 (2016-09-20) 1244次浏览
#include <stdio.h>
#include <stdlib.h>
#define  ERROR -1
#define  OK 0
int testFunc(int * pIntA)
{
if (NULL == pIntA)
{
return ERROR;
}
//*pIntA = 0x1000;
return OK;
}
int main()
{
char *pcTestA;
pcTestA = (char *)malloc(sizeof(char));
if(NULL == pcTestA)
{
return ERROR;
}
int retVal = testFunc((int*)pcTestA);
free(pcTestA);
return OK ;
}
解决方案

20

pcTestA = (char *)malloc(sizeof(char)); 后,pcTestA所指向的位置只有1个字节((sizeof(char))的空间可以合法使用
*pIntA = 0x1000; 强转后,要使用的空间为sizeof(int)个字节,一般比1大,用到了不该用的,很可能要出问题

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明强制类型转换失败,什么原因列
喜欢 (0)
[1034331897@qq.com]
分享 (0)