|
|
Answers to Memory Management in C and C++
| |
Question #1
When 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
Assuming that myObj is less than 1000 bytes, is there anything wrong with
this code?
char x[1000];
myObj *obj = reinterpret_cast<myObj *>(x);
new (obj) myObj;
a) Nope, it works fine b) Yes, there could be byte alignment issues
c) Yes, the syntax for calling new is
incorrect
Question #3
What is the functional difference between
myObj *x = new myObj[100];
delete x;
and
myObj *x = new myObj[100];
delete [] x;
a) There is none; they both work as
expected
b) They both do nothing.
c) The first will not invoke all myObj destructors
Question #4
What is wrong with the following code?
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
What is one possible symptom of having called free on the same block of
memory twice?
a) Nothing, calling free twice on one block of memory always works fine b) Malloc might always return the same block of memory
c) You cannot free any memory in the future
|
Question #6 What's wrong with this line of code?
int *x = NULL;
delete x;
a) It causes a segmentation fault when
delete tries to access NULL b) Nothing
c) It is undefined behavior
Question #7
Assuming this code were being compiled using a standards-conforming C++,
what is wrong with it?
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
What is the default behavior of the normal new operator failing?
a) This is left up to the implementation to decide
b) It returns NULL c) It throws an exception
Question #9
What is a difficulty that arises with handling out of memory errors?
a) Many cleanup operations require extra memory
b) Running out of memory rarely happens in systems that interact with
users
c) Once you've run out of memory, your
program cannot continue
Question #10
What is the result of this code?
myObj *foo = operator new(sizeof(foo));
a) That's not legal syntax!
b) foo has memory allocated for it, but
is not constructed
c) foo has memory allocated for it, and
is fully constructed
|
|
|
|