Free() knows how many bytes of memory to free but can delete[] do same thing? What if we allocate from stack instead of heap, do they work flawlessly with free() and delete[] ? Last question: do we need to assign to NULL at the end?
#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;
}
Thank you.