We pay for user submitted tutorials and articles that we publish. Anyone can send in a contributionLearn More
Recently, I ran into an interesting job interview question in C++ which I want to share. Lets take a look at the following code:
// Option A. char str1 = "example"; str1 = 'a'; // Option B. char* str2 = "example"; str2 = 'a';
What would happen if we compile and run this code ?
Take your time and think about it…
Before answering this question, lets first understand this code and discuss both options:
Array of 8 characters (‘\0′ is added) is allocated on the stack.
An unnamed, static array of characters is stored in the read only data segment. Str2 is a pointer that is allocated on the stack, but it points to the read only array’s first character.
So, when we try to change the data in the first option, every thing is fine and str1 becomes “eaample”. But when trying to change the data that is pointed by str2 (read only data), “Access violation writing location …” exception is raised.
The correct answer is: 3. This code compiles but option B will produce a run time error.
I must point out that some compilers have the option -fwritable-strings which makes the constant strings non-constant, but this is for compilation of old code.
So, what do you have to say? Do you have more interesting “job interview” questions? Would you like to see a weekly “Job Interview Challenge” in Dev102?
Tags :Access violationArrayC#chardata segmentjob interviewmemory managementpointerRead OnlystackUnmanaged
Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd