Answers to Memory Management in C and C++Question #1When will this line fail to compile: new myObj[100];a) Never b) When myObj is too large to fit into memory c) When myObj has no default constructor Question #2 char x[1000]; myObj *obj = reinterpret_cast<myObj *>(x); new (obj) myObj;
a) Nope, it works fine myObj *x = new myObj[100]; delete x;and myObj *x = new myObj[100]; delete [] x;
a) There is none; they both work as
expected
int * x = (int *) malloc(100 * sizeof(int)); x = realloc(x, sizeof(int) * 200);a) If realloc fails, then the original memory is lost b) Nothing, realloc is guaranteed to succeed (by returning the original pointer) c) Nothing, realloc frees the original memory passed to it Question #5
a) Nothing, calling free twice on one block of memory always works fine int *x = NULL; delete x;
a) It causes a segmentation fault when
delete tries to access NULL
int * x = malloc(100 * sizeof(int)); x = realloc(x, sizeof(int) * 200);a) malloc is undefined in C++, you can only allocate memory using new b) Invalid cast from a void* to an int* c) Nothing is wrong with this code Question #8
a) This is left up to the implementation to decide
a) Many cleanup operations require extra memory myObj *foo = operator new(sizeof(foo));
a) That's not legal syntax! |