Thursday 5 November 2020

Chapter 18 // Exercise 4 - Principles & Practice Using C++

In this exercise I am using Visual Studio 2017 and the std_lib_facilities header provided by Stroustrup.

Chapter 18 // Exercise 4

Consider what happens if you give strdup(), findx(), and strcmp() an argument that is not a C-style string. Try it! First figure out how to get a char* that doesn't point to a zero-terminated array of characters and then use it (never do this in real - non-experimental - code; it can create havoc). 

Try it with free-store allocated and stack-allocated "fake C-style strings." If the results looks reasonable, turn off debug mode. Redesign and re-implement those three functions so that they take another argument giving the maximum number of elements allowed in argument strings. Then test that with correct C-style strings and "bad" strings.

Github: https://github.com/l-paz91/principles-practice/blob/master/Chapter%2018/Exercise%204

My 'fake' c-style string of 'windows' reported a length of 20 and as such printed garbage after printing windows. It also didn't find 'd' in windows; it returned 'ws'. FindX returned a c-style string so strcmp turned out to work but I think that was just a fluke. That was all just in debug mode. When I switched to release it all worked properly. Visual Studio; built by wizards.

Interestingly when I examined the disassembly of the release build, the initial fake string (which was reporting a size of 8) was still being given 20 spaces:

Chapter 18 // Exercise 4 - Principles & Practice Using C++

646E6977h is "dniw" or "wind"...I'm not sure where the "ows" has gone but it's being moved into the esp register with an offset of 20. Even stranger is that after the initialisation, VS reports that Windows has 7 elements but the last 3 are garbage.

It then clears the eax register to 0 and continues assigning the rest of characters of the fake string and at esp+24 adds 'w' and 'o'. Then at esp+26 adds 's'.

The disassembly from the debug build is much more straightforward but uses more cycles:

Chapter 18 // Exercise 4 - Principles & Practice Using C++

From what I can gather here, it's storing 'w' into chars and then the rest at an offset in the ebp register. 

One day, I hope I'm as smart as the people who build compilers because this is fascinating. But anyway, the exercise still needs completing.

Instead of relying on my custom function arrayLength() to supply the length, I added an argument to strcmp, strdup and findx to take in the length of the array.


No comments:

Post a Comment