Reputation: 894
I've been trying to convert a const char to a char for the past 30 minutes. Here's what I've got.
string atr;
getline(cin,atr); // Start off with a string because getline takes nothing else.
const char *buffA = atr.c_str(); // Create a const char of the string converted to a const char.
char *buff = ""; // Create a new char to hold the converted result.
strcat(buff,buffA); // Do the conversion.
parseargs(buff); // Pass the data on.
However, I get an unhandled exception. I have no idea why. I literally just typed 'try' into the console as my only argument.
Upvotes: 1
Views: 251
Reputation: 117691
Try using C++ instead of C idioms:
std::vector<char> data(atr.begin(), atr.end());
data.push_back('\0');
parseargs(&data[0]);
Upvotes: 8
Reputation: 9354
This
char *buff = ""; // Create a new char to hold the converted result.
creates a char *
that points to (probably read-only) memory of about 1 byte in extent. This:
strcat(buff,buffA); // Do the conversion.
attempts to overwrite that (probably read-only) memory of 1 or so bytes with an arbitrary string.
The chances are this will promptly crash. If the memory is read only, it will crash immediately. If the memory is not read only it will stomp over random data, resulting in very undefined behaviour.
Why on earth do you want to do that? Does parseArgs
actually need a modifiable string? It's parsing arguments, it shouldn't need to change them. If it's really necessary, use a std::vector<char>
and pass the address of the first element and hope that all it does is poke the contents of the array, rather than (say) running over the end.
Upvotes: 2
Reputation: 153919
There are two things wrong with your code. First, you
initialize a char*
with a string literal. This uses
a deprecated convertion; the type of a string literal is char
const[]
(which converts to char const*
, not to char*
),
because any attempt to modify the literal is undefined behavior.
The second is that your string literal is only one char
long,
so even if you could write to it, unless atr
was empty, you're
writing beyond the end of the buffer.
You don't tell us anything about parseargs
. If it doesn't
modify it's argument, you can just pass it atr.c_str()
, and be
done with it. (If it's a legacy function which ignores const,
you may have to use a const_cast
here.) If it does modify its
argument (say because it uses strtok
), then you'll have to
explicitly push a '\0'
onto the end of atr
, and then pass it
&atr[0]
. (Not a particularly clean solution, but if you're
not using atr
afterwards, it should work.)
Upvotes: 5
Reputation: 13207
Both your contents of buff
and buffA
are in read-only memory of the process.
You will actually need to new
your buff
like
char* buff = new char[32];
This provides memory from the free-store and you can then strcat
the string from buffA
to buff
.
You should prefer strncat
, though to avoid buffer-overruns and delete
your buff
eventually.
Upvotes: 4