-2

I can not get my string data back using pointer to the char array. Could you give me an explanation what i am doing wrong please.

#include "stdafx.h"
#include <conio.h>
#include <string>

using namespace std;

string GetString()
{
    return string("255");
}

int _tmain(int argc, _TCHAR* argv[])
{
    char* str_p = const_cast<char*>(GetString().c_str());
    printf("Pointer : %s\n", str_p);
    string str;
    str = str_p[0];
    str += str_p[1];
    str += str_p[2];
    printf("Constructed : %s\n", str.c_str());

    _getch();
    return 0;
}

The console output is :

Pointer :
Constructed :
DevCpp
  • 3
  • 3
  • 1
    You are taking the address of a temporary object. As soon as that line end the c-string will be destroyed and you have a dangling pointer. – NathanOliver Apr 22 '15 at 19:33
  • The string returned from the call to GetString() only stays alive until the semicolon at the end of that line. The str_p pointer probably points to an internal field of that string which is about to be destroyed. If you want the string to stay alive (and so also the pointer returned by c_str() to remain valid) then assign the result to a named local first. – Mike Vine Apr 22 '15 at 19:43
  • 1
    Also the casting away of const-ness is unnecessary and dangerous. – Mike Vine Apr 22 '15 at 19:44

1 Answers1

1

There is a lot wrong with this line:

char* str_p = const_cast<char*>(GetString().c_str());

GetString() returns a temporary string. It gets destroyed at the end of the line. So you end up with a dangling pointer to internal data that was already deallocated. Furthermore, const_cast is something you should only ever be using if you really really really need it - editing data directly is just asking for trouble.

If you want a pointer into that string, the right thing to do is:

string old = GetString();        // make sure it doesn't go out of scope
const char* str_p = old.c_str(); // while this pointer is around
Barry
  • 247,587
  • 26
  • 487
  • 819