-2

Here is the code I wrote. It makes a const char* to uppercase. First argument is a pointer to a const char* and the second argument is a temp place holder which is allocated in the heap.

#include <cctype> #include <cstring> #include <iostream> void c_strtoupp(const char** c_str, char* _temp) { std::strcpy(_temp, *c_str); for (unsigned int i = 0; i < std::strlen(*c_str) + 1; i++) _temp[i] = static_cast<char>(std::toupper(_temp[i])); *c_str = _temp; } int main() { const char** s = new const char*("alexander"); char* _t = new char[std::strlen(*s) + 1]; c_strtoupp(s, _t); std::cout << *s << '\n'; delete s; s = nullptr; delete[] _t; _t = nullptr; //std::cin.get(); // to pause console return 0; } 
5
  • 4
    "Is the following code considered bad practice?" yes - use std::string instead Commented Nov 16, 2018 at 13:52
  • This doesn't create a string: const char** s = new const char*("alexander"); It create a pointer to a list of pointers to string. Use std::String instead. Commented Nov 16, 2018 at 13:52
  • If you wan't to learn raw pointers, and get help here, i think you are better off sticking to writing 'c' programs only and marking your questions with 'c' tag only - not c++. Commented Nov 16, 2018 at 13:55
  • 1
    Stop the insanity Commented Nov 16, 2018 at 14:15
  • Why the double star for s? Commented Nov 16, 2018 at 14:38

1 Answer 1

1

Is the following code considered bad practice?

Yes. Bare pointers to dynamic resources are considered a bad practice. Also, calling std::strlen inside a loop condition is bad practice - you can calculate the length once outside the loop and store it in a variable.

You don't need smart pointers either. A good practice is to use std::string to contain a dynamic string.


Also, setting local pointer to null after deleting it is usually, as it is in this case, pointless because it is clear that _t is immediately going to be out of scope anyway.

Sign up to request clarification or add additional context in comments.

1 Comment

Setting a pointer to null good Practice offer or redundant. That depends on the defensive posture of your code and if it is going to be maintained over time. If code is added after the last use, and the pointer is not set to null the memory it points to may be re-used (use after free). Which would be bad practice but does happen. Setting it to null is also zero runtime cost in production since it will almost certainly be optimized away. Of course the best practice is not to use bare pointers when smart pointers are available and adopt a different code idiom, like defensive C, otherwise.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.