Recently some people have been pestering me to post back up my C++ quizzes. So…without further ado here is the first one. The answers will be posted later.
- Given the following three lines of code, answer these questions
int* p = new int[10];
int* j = p + 11;
int* k = p + 10;- Is the second line well defined behavior?
- If the second line is well defined, where does the pointer point to?
- What are some of the legal operations that can be performed on the third pointer?
- What output should the following lines of code produce?
int a = 10;
std::cout<<a<<a++<<--a; - Assuming the function called in the following block of code has no default parameters, and that no operators are overloaded, how many parameters does it take? Which objects are passed to it?
f((a, b, c), d, e, ((g, h), i)); - Assuming the function called in the following block of code takes an A* and a B*, what is potentially wrong with the code?
f(new A(), new B());
Washu
October 7, 2009 at 10:05 pm
1.1 – No, it is undefined behavior as the only allowable range for pointers derived from
pis[p, p + 10].1.2 – Since the behavior is undefined, this is meaningless
1.3 – Comparison between other pointers derived from
p. Decrement and subtraction by any value that would keepkwithin[p, p + 10]. Subtraction betweenkand any other pointer derived frompto obtain aptrdiff_t.2. Undefined behavior. Due to
abeing a scalar type, and the lack of sequence points present, along with the fact that function parameters are evaluated in an unspecified order (but are guaranteed to be evaluated prior to the function call),awill be modified more than once between sequence points. This results in undefined behavior per the standard.3. the
, operatorwill evaluate its arguments from left to right, returning the result of the rightmost expression. As such the parameters passed tofare:c,d,e, andi.4. There is a potential for the first or second new to be called, and then the alternate new to throw an exception, causing a leak. Also, there may be construction order dependencies between
AandB, and due to the implementation defined order in which function parameters are evaluated, that dependency could be violated. There is the potential for leakage fromf, although that’s a non-issue since we appear to be transferring ownership of the pointer tof.