0

I'm newbie in cpp and I'm having some doubt about memory leaking. I have this Method:

void MyClass::setBright(int bright){
    std::string str = "sudo light -S ";
    str+= std::to_string(bright);
    const char *c = str.c_str();
    std::system(c);
    std::cout<< "brightsness adress is " << &c;
    //delete [] c;
};

This Method is called multiple times, and I'm not sure if every time that I create const char *c it'll allocate a new address in my heap memory and the last const char *c will not be released. If this occurs, how can I avoid that?
I appreciate any help!

  • 1
    In C++ the rule is: you must `delete` everything you `new`. There's nothing that the shown code `new`s, so what makes you think that you have to `delete` anything? – Sam Varshavchik Jul 04 '21 at 23:57
  • 3
    `const char *c = str.c_str()` isn't performing any allocation, except for the automatic-duration pointer itself. The pointed-to array of characters is managed by `str`. It's not creating a new copy of `str`'s underlying character array, just returning a pointer to the existing one. – Nathan Pierson Jul 04 '21 at 23:57
  • @SamVarshavchik, Like I said, I'm newbie. It would be nice to have more empathy – Mario De Santis Jul 05 '21 at 00:00
  • @SamVarshavchik There are exceptions to that rule. For example `std::make_uinque`, `std::unique_ptr::release` and `delete`. – 273K Jul 05 '21 at 00:09
  • @JosephSible-ReinstateMonica, yes! Your comment and Nathan's comment helped me. – Mario De Santis Jul 05 '21 at 00:39
  • Handy reading: [What is meant by Resource Acquisition is Initialization (RAII)?](https://stackoverflow.com/questions/2321511/what-is-meant-by-resource-acquisition-is-initialization-raii). `std::string` fully observes RAII. It [owns](https://stackoverflow.com/questions/49024982/what-is-ownership-of-resources-or-pointers) the `char` array returned by `c_str()` and will manage [proper copy and move semantics as well as the destuction of the array(if necessary)](https://en.cppreference.com/w/cpp/language/rule_of_three). – user4581301 Jul 05 '21 at 01:59

0 Answers0