RSS
 

A Simple C++ Quiz

07 Oct

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.

  1. Given the following three lines of code, answer these questions
    int* p = new int[10];
    int* j = p + 11;
    int* k = p + 10;

    1. Is the second line well defined behavior?
    2. If the second line is well defined, where does the pointer point to?
    3. What are some of the legal operations that can be performed on the third pointer?
  2. What output should the following lines of code produce?
    int a = 10;
    std::cout<<a<<a++<<--a;
  3. 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));
  4. 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());
 
1 Comment

Posted in C++, Quizzes

 
  1. Washu

    October 7, 2009 at 10:05 pm

    1.1 – No, it is undefined behavior as the only allowable range for pointers derived from p is [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 keep k within [p, p + 10]. Subtraction between k and any other pointer derived from p to obtain a ptrdiff_t.

    2. Undefined behavior. Due to a being 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), a will be modified more than once between sequence points. This results in undefined behavior per the standard.

    3. the , operator will evaluate its arguments from left to right, returning the result of the rightmost expression. As such the parameters passed to f are: c, d, e, and i.

    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 A and B, and due to the implementation defined order in which function parameters are evaluated, that dependency could be violated. There is the potential for leakage from f, although that’s a non-issue since we appear to be transferring ownership of the pointer to f.