Page 1 of 3 123 LastLast
Results 1 to 10 of 26
  1. #1
    Join Date
    Jul 2008
    Location
    Essex, United Kingdom
    Posts
    248

    Two Simple C++ Examples I Need Clarifying

    Hey everyone,

    I've recently downloaded a C++ quiz in which i need some clarification on a couple of questions i believe are a bit suspicious and may have made a mistake. They have provided you four possible answers. The first question is:

    Q: If a program declared four variables, one of type int, one of type float, one of type char, and one of type bool, which variable would occupy the least space in memory?
    a) int
    b) char
    c) float
    d) bool

    If i had to pick an answer, it would be bool. But isn't it true that a variable in C++ has a minimum size of 8 bytes? If this is true a bool and char variable would be the same byte size in memory?

    Q: What, if anything, is wrong with the following program?

    Code:
    int * EncryptNumber(int w)
    {
        int *z_ptr = &w;
        w++;
        return z_ptr;
    }
    
    void main()
    {
        int a;
        cin >> a;
        cout << *(EncryptNumber(a));
    }
    a) The pointer 'z_ptr' is returned and the value of the variable it points to is displayed on the screen.
    b) The pointer 'z_ptr' is returned and its memory address is displayed on the screen.
    c) The pointer 'z_ptr' is not declared in an appropriate manner, causing the program to crash.
    d) The pointer 'z_ptr' is returned but the variable it points to goes out of scope, causing the program to crash.

    In this question, my initial thinking is that a is copied by value in the EncryptNumber function, so a new copy of a is added in the function's stack - with a new memory address. So when the z_ptr is returned i'd have thought the variable it points to goes out of scope since the function's stack has been destroyed when it ended. Therefore, the answer would be d). However when i type this out in Visual Studio, it returns the value of a, implying the function copies by reference and not by value? Am i missing something here?

    Any help will be tremendously appreciated. Thanks!
    Last edited by da1bu89; 03-02-2012 at 08:38 PM.

  2. #2
    Join Date
    Jul 2010
    Posts
    472
    I'd... be really interested in knowing where you got these quizzes. You have the right idea in the first one, and are correct in saying the sizes are the same between a bool and a char, displayed here. In the second one, it asks: "What, if anything, is wrong with the following program?" and... there isn't an option saying "it's fine".

    That aside, when you do this in Visual Studio (I didn't completely follow the explanation), what value do you submit for the cin, and what value is returned in the cout? Is it one greater than the number you submitted, or is it the same number?
    "It's most impressive when it's least expected."

  3. #3
    Join Date
    Jul 2008
    Location
    Essex, United Kingdom
    Posts
    248
    Thanks for the response PDI247. The quiz is actually provided by a respectable University, i won't mention which one. There are another two questions on there with errors i am certain of, not very impressive.

    Alright, so a bool and char variable take 1 byte in memory, so they're the same. That's what i thought.

    Now reading your response i think i've figured out the second question. I inputted an integer value for the cin, so by the time EncryptNumber is called, 'a' has an integer value stored.

    So the function firstly copies 'a' into it's scope, or stack, since we are passing by value and not reference. Then a pointer is declared and assigned the address of the copied variable - 'a' in this case. Then 'a' is incremented by a value of one, so if we assigned 'a' 10 with the cin, the copied variable inside EncryptNumber will now be 11. Then we return the address of the pointer - it points to a local variable inside the function with a value of 11.

    Back in the main function the value is de-referenced and displayed with cout. Then the local variables, z_ptr and w, are destroyed when the function comes to an end. If we tried to access them now visual studio would complain about undeclared identifiers.

    That's what Visual Studio is doing. I guess the address is returned to cout, and then the function ends consequently destroyed it's local variables. So the answer to the question would infact be a).
    Last edited by da1bu89; 03-02-2012 at 10:55 PM.

  4. #4
    Join Date
    Jun 2003
    Location
    Trier, Germany
    Posts
    1,350
    I'm not very happy with the answering options on the second question. The main problem here is that dereferencing an invalid pointer will never lead to a crash in ISO C++. It will lead to a state called undefined behavior, which is fancy-speak for "anything could happen". Could crash, could work fine, could format your hard drive and destroy the universe... it's undefined. Which is a *lot* worse than a simple crash because it's a lot harder to detect. As you've observed, the code ran fine on VS, but that doesn't mean it's correct.

    This thing about undefined behavior is actually an important feature of C++: It allows compilers to do all kinds of optimizations, as they delegate certain responsibilities to the programmer. Unfortunately, if you accidentally write code with undefined behavior, it can be very hard to debug, since you may not even be aware that there is an error until you change the circumstances under which the code is running.

    Your initial train of thought for that question was correct: The function returns a pointer to a local variable, which is not valid. The correct answer to the question 'What happens when you dereference that pointer?' would be: There's no way to know that. It's undefined.

  5. #5
    Join Date
    Oct 2006
    Posts
    1,548
    da1bug89, its only really working because when the function returned, the values are still on the stack, they're not meant to be used, but they're still there. Now, if you were to call a function after getting the value back, then you would get an incorrect value when dereferencing, as the stack has now been overwritten.

    For example:

    Code:
    #include<iostream>
    using namespace std;
    
    int * EncryptNumber(int w)
    {
        int *z_ptr = &w;
        w++;
        return z_ptr;
    }
    
    int MakeUseOfStack( int e )
    {
    	int a = 1, b = 2, c = 3, d = 4;
    	return a*e*b*e*c*e*d*e;
    }
    
    void main()
    {
        int a;
        cin >> a;
    
    	int* pResult = EncryptNumber(a);
    
    	int result2 = MakeUseOfStack(99);
    
    	cout << *pResult;
    }
    I get "99" when I dereference pResult.
    Last edited by wforl; 03-03-2012 at 04:59 AM.
    [quote][\quote]

  6. #6
    Join Date
    Jul 2008
    Location
    Essex, United Kingdom
    Posts
    248
    Yes exactly wfori. If you returned the pointer to a variable and tried to use it the value would be undefined. In this question's example everthing works, but it isn't good programming practice... very odd. Thanks anyway.

  7. #7
    Join Date
    Feb 2005
    Location
    Bellevue, WA
    Posts
    3,251
    Your "respectable university" needs to get some better C++ teachers. There are so many things wrong with all of that code.

    And returning a pointer to a variable defined in a function is not just poor programming practice, that's the type of things that leads to some potentially serious security issues. Never do undefined behavior. =)

    And stop with the "void main"! AGH!!

    "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning." ~Rich Cook

  8. #8
    Join Date
    Jul 2006
    Location
    San Diego, CA, USA
    Posts
    897
    It appears the code was meant to be poorly written such that the student could give the reason what would happen when run. I agree with the assessments given by those who responded in that the more precise answer was not given in the list of choices.
    Code Fearlessly!

  9. #9
    Join Date
    Jun 2003
    Location
    Trier, Germany
    Posts
    1,350
    Quote Originally Posted by smjones View Post
    It appears the code was meant to be poorly written such that the student could give the reason what would happen when run.
    I don't know, I'm with owensd here. The way the question were posed and the given answers indicate that this quiz was put together by someone who does not know C++ very well. Which doesn't say too much about the university - i've seen code like this from more than one renowned university. They have good programmers and bad programmers just like everywhere else, it's just that with the better universities, the ratio is more on the good side.

  10. #10
    Join Date
    Feb 2005
    Location
    Bellevue, WA
    Posts
    3,251
    The real correct answer to question #2 is that it won't compile.

    Code:
    
    [~]$ clang main.cpp
    main.cpp:13:1: error: 'main' must return 'int'
    void main()
    ^
    1 error generated.


    It's not about a precise answer, there is no correct answer given for either question.

    "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning." ~Rich Cook

Page 1 of 3 123 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •