Pages

Saturday, 26 September 2020

Chapter 17 // 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 17 // Exercise 4

Write a function, char* strdup(const char* c), that copies a C-style string into memory it allocates on the free store. Do not use any standard library functions.

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

With const pointers I find it really stupid that you can't change the object that the pointer is pointing at, but you can change what the pointer is pointing at. In this exercise, c can be changed to point at some random garbage address but god forbid you want to assign the pointer to a non-const pointer. Unreal has a problem with this because pretty much everything gets passed round as const pointers but this allows for people to change what it's pointing at and no one will be none the wiser because it says const in the argument parameters. A lot of programmers assume (and rightly so) that this means their arguments won't be modified in the function body.

We have a senior engineer who prefers us all to use const references as you cannot change the object OR change what it's pointing at and less mistakes can be made.

Also, strdup() is a deprecated std library function so I renamed it so it would compile.

No comments:

Post a Comment