I have this piece of code in my program. I'm trying to send an RSA key which is stored in buf variable here, but c_str() seems to cut string stored in buf...
int client::sendData(SOCKET &ss, std::string buf) {
if (cipher) buf = client_rsa->encrypt(buf);
char sendbuf[DEFAULT_BUFLEN];
strcpy_s(sendbuf, buf.c_str());
std::cout << "BUF: " << buf <<"\nSENDBUF: " << sendbuf << "\n";
int iSendResult = send( ss, sendbuf, buf.length(), 0 );
if (iSendResult == SOCKET_ERROR) {
printf("send failed: %d\n", WSAGetLastError());
closesocket(ss);
WSACleanup();
return 1;
}
return 0;
}
Here is what I get on the console after running this function:
BUF: ♠☻ Ą
꼣ŚĚÔ►ĹUx↑a↕ęý«$úP¶Ł×VÎŰ..Ů∟É═pů,ܨAk⌂Îăů↕ĺxw▓►ŔD ;▼<♂▀&¬╔6Č,ŘG+§ťĘă
SENDBUF: ♠☻
Only first to chars are copied... Anyone has any idea how to fix this... or copy it without using c_str() function. I'll be very grateful for any help.
10 3181
I have this piece of code in my program. I'm trying to send an RSA key which is stored in buf variable here, but c_str() seems to cut string stored in buf... - int client::sendData(SOCKET &ss, std::string buf) {
-
if (cipher) buf = client_rsa->encrypt(buf);
-
char sendbuf[DEFAULT_BUFLEN];
-
strcpy_s(sendbuf, buf.c_str());
-
std::cout << "BUF: " << buf <<"\nSENDBUF: " << sendbuf << "\n";
-
int iSendResult = send( ss, sendbuf, buf.length(), 0 );
-
if (iSendResult == SOCKET_ERROR) {
-
printf("send failed: %d\n", WSAGetLastError());
-
closesocket(ss);
-
WSACleanup();
-
return 1;
-
}
-
return 0;
-
}
Here is what I get on the console after running this function:
BUF: ♠☻ Ą
꼣ŚĚÔ►ĹUx↑a↕ęý«$úP¶Ł×VÎŰ..Ů∟É═pů,ܨAk⌂Îăů↕ĺxw▓►ŔD ;▼<♂▀&¬╔6Č,ŘG+§ťĘă
SENDBUF: ♠☻
Only first two chars are copied... Anyone has any idea how to fix this... or copy it without using c_str() function. I'll be very grateful for any help.
Are you sure that c_str() cuts the data,have you tried:
?
Other method is to use data,it returns a const char * to the first element in the string,however be aware that it doesn't append '\0',because '\0' is null terminator only for char arrays,but not for string object,or to quote msn:
The return type for data is not a valid C-string, because no null character gets appended. The null character ' \0 ' is used as a special character in a C-string to mark the end of the string, but has no special meaning in an object of type string and may be a part of the string object just like any other character.
Ps:Also,please use code tags around your code.Syntax is [code=<lang>] your code and then close it with /code in square brackets.
Savage
Are you sure that c_str() cuts the data,have you tried:
?
Yes, I tried that and it's c_str(), which does that... but not only. I also tried buf.copy(...) and data(). All give the same effect. What makes it even more strange, I have also this piece of code in other class in my program and it works fine: -
void Rsa::importKey(string key)
-
{
-
char *in_c = const_cast< char * >(key.c_str());
-
BYTE *key_byte = new BYTE[key.length()];
-
for(int i = 0; i < key.length(); i++)
-
{
-
key_byte[i] = in_c[i];
-
}
-
-
if(!CryptImportKey(hCryptProv,key_byte,key.length(),0,0,&hXchgKey))
-
{
-
printf("Error %x during CryptImportKey!\n", GetLastError());
-
}
-
}
-
Yes, I tried that and it's c_str(), which does that... but not only. I also tried buf.copy(...) and data(). All give the same effect. What makes it even more strange, I have also this piece of code in other class in my program and it works fine: -
void Rsa::importKey(string key)
-
{
-
char *in_c = const_cast< char * >(key.c_str());
-
BYTE *key_byte = new BYTE[key.length()];
-
for(int i = 0; i < key.length(); i++)
-
{
-
key_byte[i] = in_c[i];
-
}
-
-
if(!CryptImportKey(hCryptProv,key_byte,key.length(),0,0,&hXchgKey))
-
{
-
printf("Error %x during CryptImportKey!\n", GetLastError());
-
}
-
}
-
Does this happens too when you don't encrypt the msg?
Savage
Yes, I tried that and it's c_str(), which does that... but not only. I also tried buf.copy(...) and data(). All give the same effect. What makes it even more strange, I have also this piece of code in other class in my program and it works fine: -
void Rsa::importKey(string key)
-
{
-
char *in_c = const_cast< char * >(key.c_str());
-
BYTE *key_byte = new BYTE[key.length()];
-
for(int i = 0; i < key.length(); i++)
-
{
-
key_byte[i] = in_c[i];
-
}
-
-
if(!CryptImportKey(hCryptProv,key_byte,key.length(),0,0,&hXchgKey))
-
{
-
printf("Error %x during CryptImportKey!\n", GetLastError());
-
}
-
}
-
Also I don't see you here freeing that allocated memory,does CryptImport key takes care of it,or did you forgot to free memory?
Savage
Does this happens too when you don't encrypt the msg?
Savage
No, it does not happen. When I'm trying to send normal string like "hello" etc., it works fine. It happens just with this key
Also I don't see you here freeing that allocated memory,does CryptImport key takes care of it,or did you forgot to free memory?
Savage
That's right... Memory is not freed. I''ll take care of this. Thanks.
No, it does not happen. When I'm trying to send normal string like "hello" etc., it works fine. It happens just with this key
That's right... Memory is not freed. I''ll take care of this. Thanks.
Then it must set '\0' as third character,thus terminating the char array.Are you using third party encrypt function,or your own?If you are using your own don't let it append '\0' until it has encrypted whole message.
Savage
I'm using wincrypt library.
I managed to solve this problem. What happens here is really very strange to me... I had to do something like this: -
int client::sendData(SOCKET &ss, std::string buf) {
-
if (cipher) buf = client_rsa->encrypt(buf);
-
char* sendbuf = const_cast< char * >(buf.c_str());
-
char *to_send = new char[buf.length()];
-
for(int i = 0; i < buf.length(); i++)
-
{
-
to_send[i] = sendbuf[i];
-
}
-
int iSendResult = send( ss, to_send, buf.length(), 0 );
-
if (iSendResult == SOCKET_ERROR) {
-
printf("send failed: %d\n", WSAGetLastError());
-
closesocket(ss);
-
WSACleanup();
-
return 1;
-
}
-
return 0;
-
}
-
It gives these results:
buf: ♠☻ Ą RSA1 ♦ ☺ ☺ E6=ĺÉ˙QEk¸š█oĐlţŔç╩ĹĘ↕i♀E0‼ŞJč╬M♣ɬă|¤pumî►2`╔ä◄m┬ ┤ ńQ§
▀*lş:HŮ▒Ľ┤˛╗↨fUóyźÍ╔║Z¨ÎŠ█'►đ*ë↕&♣k}´Žr\°Wç' ŚZÁ´čz2ĚČżŰqfÖ5
buf.c_str(): ♠☻
sendbuf: ♠☻
to_send: ♠☻ Ą RSA1 ♦ ☺ ☺ E6=ĺÉ˙QEk¸š█oĐlţŔç╩ĹĘ↕i♀E0‼ŞJč╬M♣ɬă|¤pumî►2`╔ä◄m┬ ┤
▀*lş:HŮ▒Ľ┤˛╗çř-r↨fUóyźÍ╔║Z¨ÎŠ█'►đ*ë↕&♣k}´Žr\°Wç' ŚZÁ´čz2ĚČżŰqfÖ5
I cannot explain this, but at least it works now. Thanks for all help.
I'm using wincrypt library.
I managed to solve this problem. What happens here is really very strange to me... I had to do something like this: -
int client::sendData(SOCKET &ss, std::string buf) {
-
if (cipher) buf = client_rsa->encrypt(buf);
-
char* sendbuf = const_cast< char * >(buf.c_str());
-
char *to_send = new char[buf.length()];
-
for(int i = 0; i < buf.length(); i++)
-
{
-
to_send[i] = sendbuf[i];
-
}
-
int iSendResult = send( ss, to_send, buf.length(), 0 );
-
if (iSendResult == SOCKET_ERROR) {
-
printf("send failed: %d\n", WSAGetLastError());
-
closesocket(ss);
-
WSACleanup();
-
return 1;
-
}
-
return 0;
-
}
-
It gives these results:
buf: ♠☻ Ą RSA1 ♦ ☺ ☺ E6=ĺÉ˙QEk¸š█oĐlţŔç╩ĹĘ↕i♀E0‼ŞJč╬M♣ɬă|¤pumî►2`╔ä◄m┬ ┤ ńQ§
▀*lş:HŮ▒Ľ┤˛╗↨fUóyźÍ╔║Z¨ÎŠ█'►đ*ë↕&♣k}´Žr\°Wç' ŚZÁ´čz2ĚČżŰqfÖ5
buf.c_str(): ♠☻
sendbuf: ♠☻
to_send: ♠☻ Ą RSA1 ♦ ☺ ☺ E6=ĺÉ˙QEk¸š█oĐlţŔç╩ĹĘ↕i♀E0‼ŞJč╬M♣ɬă|¤pumî►2`╔ä◄m┬ ┤
▀*lş:HŮ▒Ľ┤˛╗çř-r↨fUóyźÍ╔║Z¨ÎŠ█'►đ*ë↕&♣k}´Žr\°Wç' ŚZÁ´čz2ĚČżŰqfÖ5
I cannot explain this, but at least it works now. Thanks for all help.
Now, if that works then: - char *sendbuf=new char[buf.lenght()];
-
for(i=0;i<buf.lenght();i++)
-
{
-
sendbuf[i]=buf[i];
-
}
should work also.
Can you please check on which place does '\0' appears for the first time?
PS:You forgot to free memory again. :D
This doesn't look right. strcpy_s has three arguments unless you specify the sioe of the target array:
char sendbuf[DEFAULT_BUFLEN];
strcpy_s(sendbuf, buf.c_str());
You should: -
char sendbuf[DEFAULT_BUFLEN];
-
strcpy_s(sendbuf, buf.c_str(), DEFAULT_BUFLEN);
-
Or you should: -
char sendbuf[DEFAULT_BUFLEN];
-
strcpy_s(sendbuf[DEFAULT_BUFLEN], buf.c_str());
-
In any case the const_cast is pointless. c_str() presents the string object as a const C string. When you copy from a source, the source should be const. Check all of your C string library functions.
Also, why a string argument??? That forces a copy of the caller's string. You should pass by reference. If you do not want the souyrce changed, then pass it as a const reference.
In any case, do not cast in C++ unless you know precisely why and and have your parent's permission.
This doesn't look right. strcpy_s has three arguments unless you specify the sioe of the target array:
You should: -
char sendbuf[DEFAULT_BUFLEN];
-
strcpy_s(sendbuf, buf.c_str(), DEFAULT_BUFLEN);
-
Or you should: -
char sendbuf[DEFAULT_BUFLEN];
-
strcpy_s(sendbuf[DEFAULT_BUFLEN], buf.c_str());
-
Actually it should be like this: -
char sendbuf[DEFAULT_BUFLEN];
-
strcpy_s(sendbuf, DEFAULT_BUFLEN, buf.c_str());
-
But it still doesn't change the fact, that sendbuf contains only two chars after this operation.
Also, why a string argument??? That forces a copy of the caller's string. You should pass by reference. If you do not want the souyrce changed, then pass it as a const reference.
In any case, do not cast in C++ unless you know precisely why and and have your parent's permission.
Yeah I know this isn't "pretty" c++ code, but that's because I have to have this project done pretty soon and I haven't been programming in c++ for a long time... The same with forgetting to free memory all the time. Thanks for good advice though.
Now, if that works then: - char *sendbuf=new char[buf.lenght()];
-
for(i=0;i<buf.lenght();i++)
-
{
-
sendbuf[i]=buf[i];
-
}
should work also.
And it does :D
Can you please check on which place does '\0' appears for the first time?
It appears as a third character for the first time so this is what causes all problems. But still, I don't understand how it all happens exactly... but I'm glad it works finally.
PS:You forgot to free memory again. :D
Damn Java habits :P
Thanks for all advice and help guys.
Sign in to post your reply or Sign up for a free account.
Similar topics
by: ree |
last post by:
I need to use a function from a wininet library, it requires the use of
const TCHAR.
The problem is the value needs to be calculated, so at the end I have this
string but I am having troubles...
|
by: Arturo DiDonna |
last post by:
Hello everyone. I am trying to compile someone else code and I am
stuck with compilation problems using
the g++ 3.3 compiler. Basically, when compiling the following code, I
get this error...
|
by: Derek |
last post by:
I'm curious about the performance of string::c_str,
so I'm wondering how it's commonly implemented. Do
most std::string implementations just keep an extra
char allocated for the NULL termination...
|
by: electrixnow |
last post by:
Help!,
I need to compile this code with static libs so it run on another XP
machine that does'nt have
MS Studio installed. When I compile now I get an ERROR:
1>------ Rebuild All started:...
|
by: shyam |
last post by:
Hi
I have a program within which i have the following statement.
sprintf(somevar,"%s/%s.%s",PREFIX.c_str( ),MIDDLE.c_str(
),SUFFIX.c_str( ) );
Here PREFIX, MIDDLE and SUFFIX are all const...
|
by: Jim Michaels |
last post by:
friend fraction& operator+=(const fraction& rhs);
fraction.h(64) Error: error: 'fraction& operator+=(const fraction&)'
must take exactly two arguments
I practically pulled this out of a C++...
|
by: v4vijayakumar |
last post by:
1. why the following program is not working as expected?
#include <iostream>
using namespace std;
int main()
{
string t("test");
wcout << (wchar_t *) t.c_str() << endl;
wcout << t.c_str()...
|
by: C++Liliput |
last post by:
I have a class of the type
class A
{
private:
std::string data;
.......
public:
const char* toString();
};
|
by: Highlander2nd |
last post by:
Hello there.
I'm Andrew Lucas, I'm a programmer for Half-Life. I've been working on stencil shadows lately, and I've been having problems saving mesh data for my models.
When I store mesh data, I...
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
| |