-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;
}
A J
  • 107
  • 1
  • 2

1 Answers1

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • 1
    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. – Richard Nov 16 '18 at 14:43