麻烦高手看看这个程序为什么不能释放内存。。。运行环境:VC++6.0C/C++ code#includeiostream.h#includestd
麻烦高手看看这个程序为什么不能释放内存。。。
运行环境:VC++6.0
- C/C++ code
#include<iostream.h>#include<stdlib.h>#define ARRAY1_SIZE 20#define ARRAY2_SIZE 60int main(){ char *charArray=NULL; char tempchar; int i; charArray=(char*)calloc(ARRAY1_SIZE,sizeof(char)); for(i=0,tempchar='A';i<ARRAY1_SIZE;i++) { charArray[i]=tempchar++; } charArray[ARRAY1_SIZE]='\0'; cout<<charArray<<endl; free(charArray); charArray=(char*)calloc(ARRAY2_SIZE,sizeof(char)); for(i=0;i<ARRAY2_SIZE;i++) { charArray[i]=tempchar++; if(tempchar>'z') { tempchar='A'; } } charArray[ARRAY2_SIZE]='\0'; cout<<charArray<<endl; free(charArray); return(0);}在DEVC++下面同样的程序能运行,VC++里面可以运行但是会弹出一个BUG警告框,麻烦高手看看问题出在哪里!
[解决办法]
charArray[ARRAY2_SIZE]='\0';越界了
[解决办法]
- C/C++ code
#include<iostream.h>#include<stdlib.h>#define ARRAY1_SIZE 20#define ARRAY2_SIZE 60int main(){ char *charArray=NULL; char tempchar; int i; charArray=(char*)calloc(ARRAY1_SIZE,sizeof(char)); for(i=0,tempchar='A';i<ARRAY1_SIZE-1;i++)//<-----------------------here { charArray[i]=tempchar++; } charArray[ARRAY1_SIZE-1]='\0';//<----------------------------------here cout<<charArray<<endl; free(charArray); charArray=(char*)calloc(ARRAY2_SIZE,sizeof(char)); for(i=0;i<ARRAY2_SIZE-1;i++)//<-----------------------------here { charArray[i]=tempchar++; if(tempchar>'z') { tempchar='A'; } } charArray[ARRAY2_SIZE-1]='\0';//<-----------------------------here cout<<charArray<<endl; free(charArray); return(0);} 