首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于free释放空间有关问题

2013-10-02 
关于free释放空间问题#include iostream#include tchar.h#include conio.hvoid PrintIt(char *szBuf

关于free释放空间问题

#include <iostream>
#include <tchar.h>
#include <conio.h>

void PrintIt(char *szBuffer,short iLength)
{
if(iLength > 2048)
return;
char szBuffCopy[2048];
memcpy(szBuffCopy,szBuffer,iLength);
printf("%s\npress the key you choosed:",szBuffCopy);
printf("to be continue...");
/*
while(_kbhit())
{
_getch();
}
while(!_kbhit())
;
*/
printf("\n");

}
int main()
{
unsigned short uiLength;
char *szInputFileLen = (char *)malloc(sizeof(uiLength));

if(!szInputFileLen) return 1;

//char *str = "simulated untrusted data.";
uiLength = sizeof("simulated untrusted data.");
printf("%d\n",uiLength);
memcpy(szInputFileLen,"simulated untrusted data.",uiLength);

PrintIt(szInputFileLen,uiLength);
free(szInputFileLen);
return 0;
}

运行上面一段程序,发现在free之后出现问题:
HEAP[memcpy_leak_test.exe]: Heap block at 00382B50 modified at 00382B7E past requested size of 26
Windows 已在 memcpy_leak_test.exe 中触发一个断点。

其原因可能是堆被损坏,这说明 memcpy_leak_test.exe 中或它所加载的任何 DLL 中有 Bug。

原因也可能是用户在 memcpy_leak_test.exe 具有焦点时按下了 F12。

输出窗口可能提供了更多诊断信息。

如果去掉free这一句,是没有任何问题的。可以运行。问题是,我free出现什么问题了,请赐教
free
[解决办法]
访问越界, 楼主还得多学下基础呀, 程序是错误很多.


int main()
{
unsigned short uiLength;
char *szInputFileLen = (char *)malloc(sizeof(uiLength)); //楼主想为字符串分配一个空间,确用了
//sizeof, 注意sizeof的用法, 这里只能求得uiLenght这个数据本身占用的内存, 也就是unsigned short
//共占2字节.  
//正确的做法应该是 
//unsigned short uiLength = 100;//任意指定你想要的初始值, 即字符串长度
//char *szInputFileLen = (char *)malloc(uiLength); //分配指定长度字节数的空间

if(!szInputFileLen) return 1;

//char *str = "simulated untrusted data.";
uiLength = sizeof("simulated untrusted data.");//对字符串求长度, 是用strlen,而不是sizeof
printf("%d\n",uiLength);
memcpy(szInputFileLen,"simulated untrusted data.",uiLength);//字符串复制,尽量使用strcpy一类的函数

PrintIt(szInputFileLen,uiLength);
free(szInputFileLen);
return 0;
}

热点排行