I'm trying to create a function that will convert a string and store it in a WSABUF structure but I'm having trouble doing so. My failings are probably due to using pointers wrongly or not fully understanding the way in which WSABUF structures work.
In the code below "stringtowsa" is supposed to take parameter one (a string) and store it in parameter two (a pointer to a WSABUF structure). It does this, but when cTemp is deleted so is the buffer.
I think that the problem is with "Return->buf = cTemp;" as this may be setting the buf pointer to point to cTemp rather than setting it to equal what is in cTemp. If this is the case, how do I set it to equal what is in cTemp? I tried but kept getting errors.
This brings me onto my next question; why do I need to set the WSABUF to equal a character array before loading it with data from the string in order to avoid an error?
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
using namespace std;
// Converts string into WSA.
void stringtowsa(string String, WSABUF * Return)
{
Return->len = String.length();
char * cTemp = new char[String.length()];
// **Problem is here**
Return->buf = cTemp;
for(unsigned int n = 0;n<String.length();n++)
{
Return->buf[n] = String[n];
}
// Note: If cTemp memory is deleted then Buf3.buf holds no data.
//delete[] cTemp;
}
void main(void)
{
WSABUF Buf3;
stringtowsa("Hello",&Buf3);
cout << "Buf3: "<<Buf3.buf<<"n";
// Wait for input and then exit.
int Blank;
cin >> Blank;
return;
}