0

I'm trying to build a utility class that I can re-use, that converts a std::string to a char*:

char* Foo::stringConvert(std::string str){
      std::string newstr = str;
      // Convert std::string to char*
      boost::scoped_array<char> writable(new char[newstr.size() + 1]);
      std::copy(newstr.begin(), newstr.end(), writable.get());
      writable[newstr.size()] = '\0'; 
      // Get the char* from the modified std::string
      return writable.get();
}

The code works when I tried to load the output from within the stringConvert function, however when used in other parts of my application, this function returns garbage.

For example:

Foo foo;
char* bar = foo.stringConvert(str);

The above code returns garbage. Is there any workaround for this kind of issue?

quarks
  • 33,478
  • 73
  • 290
  • 513
  • It would have been easier to answer the question if you hadn't omitted the code. – Andreas Brinck Jun 25 '12 at 08:55
  • @cppcoder boost::scoped_array writable(new char[newstr.size() + 1]); – quarks Jun 25 '12 at 09:04
  • You might want to have a look at http://stackoverflow.com/questions/347949 – Tony Delroy Jun 25 '12 at 09:25
  • @TonyDelroy Actually the shown in the link is basically the same with my code. I will update the code in the question for clarification – quarks Jun 25 '12 at 09:54
  • @xybrek: you haven't understood it... when you return only the .get() result, the scoped_array destructor still deletes the memory you newed while the function returns... the char* addresses that invalid memory region.... – Tony Delroy Jun 25 '12 at 13:56
  • @TonyDelroy Yah I know about that, because my code works when not passed as a function of a class. – quarks Jun 25 '12 at 18:02

2 Answers2

2

I'm going to assume writable is an object with automatic duration that destructs the char* it contains in the destructor - that's your problem - whatever writable.get() returns is no longer valid.

Just return a std::string instead, why on earth do you need a raw char *?

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
1

Why don't just use std::string.c_str()? This is a library method that does just what you need.

undefined
  • 1,354
  • 1
  • 8
  • 19
  • I can't use the c_str() function because, I will get this error: cannot convert parameter 2 from 'const char *' to 'LPSTR'(char*) – quarks Jun 25 '12 at 09:03
  • You can look here: http://stackoverflow.com/questions/342772/convert-lptstr-to-char looks similiar to your case. – undefined Jun 25 '12 at 09:54