int * p = NULL;
p = (int*)malloc(sizeof(int));
if (p == NULL)
{
/*...*/
}
/*初始化為0*/
memset(p, 0, sizeof(int));
char *ptr = (char *)malloc(10);
char name[20] ;
memcpy ( name,ptr,20); // Problem begins here
int mark[100];
...
//讓用戶輸入學(xué)生編號,設(shè)現(xiàn)實中學(xué)生編號由1開始:
cout << "請輸入學(xué)生編號(在1~100之間):"
int i;
cin >> i;
//輸出對應(yīng)學(xué)生的考試成績:
cout << info[i-1];
class Object {
private:
void* data;
const int size;
const char id;
public:
Object(int sz, char c):size(sz), id(c){
data = new char[size];
cout << "Object() " << id << " size = " << size << endl;
}
~Object(){
cout << "~Object() " << id << endl;
delete []data;
}
};
void GetMemory2(char **p, int num)
{
*p = (char *)malloc(sizeof(char) * num);
}
void Test2(void)
{
char *str = NULL;
GetMemory2(&str, 100); // 注意參數(shù)是 &str,而不是str
strcpy(str, "hello");
cout<< str << endl;
free(str);
}
void port();
void addr();
int main ()
{
addr();
port();
}
long *p ;
void port()
{
long i, j ;
j = 0;
for ( i = 0 ; i < 10 ; i++ )
{
(*p)--;
j++;
}
}
void addr()
{
long k;
k = 0;
p = &k;
}
char *GetString2(void)
{
char *p = "hello world";
return p;
}
void Test5(void)
{
char *str = NULL;
str = GetString2();
cout<< str << endl;
}
char *p = (char *) malloc(10);
strcpy(p, “hello”);free(p); // p所指的內(nèi)存被釋放,但是p所指的地址仍然不變…//忘記 釋放 strcpy(p, “world”); // 出錯
char *p = (char *) malloc(10);
strcpy(p, “hello”);
free(p); // p所指的內(nèi)存被釋放,但是p所指的地址仍然不變…
if(p != NULL) // 雖然記得,但沒有起到防錯作用
{
strcpy(p, “world”); // 出錯
}