Free() は解放するメモリのバイト数を知っていますが、delete[] で同じことができますか? ヒープではなくスタックから割り当てる場合、 free() と delete[] で問題なく動作しますか? 最後の質問: 最後に NULL を代入する必要がありますか?
#include <stdio.h>
#include <stdlib.h>
char * malloc2()
{
char * m = (char *)malloc(100);
//so malloc(10000000) cannot cause stack-overflow?
//cast from void * to char *
return m;
}
char * malloc3()
{
static char m[100];
//can [1000000] cause stack overflow?
return m;
}
char * newX()
{
char * output = new char[100];
return output;
}
int main(){
char * p = malloc2();
//sizeof(p) gives 8 because this is on 64 bit OS/CPU
free(p);
//free() knows the size of p is 100.
//Does it matter if this allocation from stack of malloc2()?
p=NULL;
char * q = malloc3();
//again, sizeof(q) fives 8
//is this allocation from stack of malloc3()?
//I dont need to free because that was from an array declaration ?
q=NULL;
//then who deletes that static array from the stack?
char * r = malloc3();
//now r and q point to same memory area ?
// then if I free q, I dont need to free r.
r=NULL;
char * s = newX();
//allocation from stack again?
//sizeof(s) gives 8, how can delete[] know its size?
delete [] s;
s=NULL;
return 0;
}
ありがとうございました。