1

In fun1() I am getting a string and I need to pass this string data to a function fun2() which takes argument char *

function2 prototype is as below

void fun2(char *p);

I am calling fun2 from fun1 as below

void fun1()
{
    fun2((char *)str.c_str());
}

Is there any chance from the conversion from const char * to char * does make any potential issues

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
krish
  • 95
  • 7
  • You're on the train to undefined behaviour if you try to modify the C-string inside and the initial data is `const`. – vsoftco Mar 07 '15 at 15:08
  • `std::string` is C++, so why is this tagged C? You shouldn't use C-style casts. If `fun2` is a legacy function which can't be changed, but WON'T modify the string, use `const_cast`. If `fun2` could modify the string, use `reinterpret_cast` but this could be undefined behavior and a whole world of hurt. – Neil Kirk Mar 07 '15 at 15:18

1 Answers1

7

If fun2 tries to modify the data pointed to by the const char* returned by std::string::c_str then it's undefined behavior.

If fun2 doesn't modify the data pointed to by p, then there won't be any problem. (But then fun2 should be declared to take a const char*, not a char*, anyway.)

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • 3
    It is only UB if the data itself is `const`. – juanchopanza Mar 07 '15 at 15:08
  • @juanchopanza you mean that if the `std::string` itself is non-const, then you are OK modifying via `c_str()`? – vsoftco Mar 07 '15 at 15:10
  • @vsoftco No, I was talking of `fun2` and casting away const-ness in general. `std::string` will have extra restrictions. – juanchopanza Mar 07 '15 at 15:14
  • Thanks for the response.const char * doesn't allow to point to another memory location .so we can change the data inside that address.please correct me if I am wrong.For me even the data is changed to that pointed address in fun2 it doesn't effect in my functionality.So can I consider that conversion as safe? – krish Mar 07 '15 at 15:18
  • Please don't do that even if it's not potentially a problem, think a good solution rather than finding a workaround. – Iharob Al Asimi Mar 07 '15 at 15:21
  • @krish `const char*` allows you to change what the pointer points to. `char* const` doesn't allow to change the pointer, but does allow to change the pointed-to data. I.e. `const` before `*` means the pointed-to data is `const`, but `const` after `*` means the pointer is `const`. You may find [this](http://stackoverflow.com/questions/10916787/string-c-str-is-const) useful. – Emil Laine Mar 07 '15 at 15:22
  • @iharibo may I know what will be the effect if i use that kind of cast there. – krish Mar 07 '15 at 15:27