Accessing array pointer in Header file? - c++

By attempting to access the TCPSocket inside my "clientArray" I get a Access Violation error. How would I access it properly?
My header file holds the TCPSocket *clientArray.
public:
TCPsocket *clientArray;
SDLNet_SocketSet aSocketSet;
bool serverOn;
It is defined within my constructor:
clientArray = new TCPsocket[maxsockets];
aSocketSet = SDLNet_AllocSocketSet(maxsockets);
It is accessible within another function of mine (it works here without issue):
void ServerSocket::waitingForConnection() {
std::cout << '\r' << flush << "Players connected: " << playersConnected << ". Listening for connection... ";
TCPsocket newsocket = SDLNet_TCP_Accept(serverSocket);
SDL_Delay(1000);
if (!newsocket){
//std::cout << '\r' << flush << "Listening for connection. ";
//std::cout << SDLNet_GetError() << std::endl;
}
else{
std::cout << '\r' << flush << "Socket (client " << slotnum + 1 << ") created successfully. " << std::endl;
clientArray[slotnum] = newsocket;
int n = SDLNet_TCP_AddSocket(aSocketSet, newsocket);
if (n < 0){
std::cout << "Client " << slotnum + 1 << " failed to connect. " << std::endl;
}
else{
char text[10];
std::cout << "Client " << slotnum + 1 << " added to client array successfully." << std::endl;
serverMessage(slotnum, "2 You are successfully connected to the server.");
std::cout << "Sent connection validation to Client " << slotnum + 1 << "." << endl;
std::cout << "Allocating player " << slotnum + 1 << " with player number ." << endl;
serverData(slotnum, '5', slotnum+1);
//ACCESSING IT HERE WITHOUT ISSUE
SDLNet_TCP_Recv(clientArray[slotnum], text, 10);
std::cout << "received text = " << text << endl;
interpretData(text);
slotnum++;
}
//SDLNet_TCP_Close(newsocket);
//SDLNet_TCP_Close(serverSocket);
//code here
}
}
However later on when I try to access it via another function, I get an Access Violation Error :
Unhandled exception at 0x00AED839 in Server.exe: 0xC0000005: Access violation reading location 0x0000000C.
I am calling the problematic function from my Game's Update function as following:
void Game::Update(){
while (g_playersConnected == 2)
{
printGrid();
serverSocket->waitForPlayer((playerTurn-1));
changeTurn();
system("pause");
}
//cout << "Game's Update is running" << endl;
};
This is my other function that is attempting to access the array :
void ServerSocket::waitForPlayer(int playerNum)
{
cout << "Waiting for player " << playerNum + 1 << " (In array : " << playerNum << ")." << endl;
char text[10];
SDLNet_TCP_Recv(clientArray[playerNum], text, 10);
std::cout << "received text = " << text << endl;
interpretData(text);
}
I have not set up Copy constructors or assignment operators and my destructors are just empty blocks at the moment.
ServerSocket::~ServerSocket(){}
Which direction should I go towards solving this issue?
All the best

Related

How to print correctly const char* struct member of a list?

I am trying to display struct members of a list in OMNeT++, all members are displayed correctly unless the member which is of type const char*. I am confused because after three push_back in the list, when I display. All the members of the last pushed element is displayed correctly even the one of type const char*. But for the two first pushed elements, the member of type cont char* display nothing, garbage or "DETAIL (Ipv4)Drones.host[3].ipv4.ip".
Ipv4Address srcAddress = recMtlsd->getSrcAddress();
Ipv4Address dstAddress = recMtlsd->getDstAddress();
const char* position = recMtlsd->getPosition();
simtime_t time = recMtlsd->getTime();
int srcID = recMtlsd->getId();
EV_DEBUG << "Source : " << srcAddress << endl;
EV_DEBUG << "Destination : " << dstAddress << endl;
EV_DEBUG << "Position : " << position << endl;
EV_DEBUG << "Time : " << time << endl;
EV_DEBUG << "Source ID: " << srcID << endl;
// All precedent displays are working correctly
/*typedef struct Mtlsd{
Ipv4Address originatorAddr, destinationAddr;
const char *position;
int originatorId;
simtime_t time;
}MTLSD;*/
MTLSD recitem;
recitem.originatorAddr = srcAddress;
recitem.originatorId = srcID;
recitem.destinationAddr = dstAddress;
recitem.position = position;
recitem.time = time;
EV_DEBUG << "Source : " << recitem.originatorAddr << endl;
EV_DEBUG << "Destination : " << recitem.dstinationAddr << endl;
EV_DEBUG << "Position : " << recitem.position << endl;
EV_DEBUG << "Time : " << recitem.time << endl;
EV_DEBUG << "Source ID: " << recitem.srcID << endl;
// All precedent displays are working correctly
/*typedef struct Mtlsd_data{
list<MTLSD> q;
int ID;
}MTLSD_DATA;*/
list<MTLSD_DATA> mtlsd_file;
auto node = find_if(mtlsd_file.begin(), mtlsd_file.end(), [=] (MTLSD_DATA const& i){return (i.ID == srcID);});
bool found = (node != mtlsd_file.end());
if (!found)
{
MTLSD_DATA recdata;
recdata.ID = srcID;
recdata.q.push_back(recitem);
mtlsd_file.push_back(recdata);
EV_DEBUG << "For node " << srcID ;
for(auto claim=mtlsd_file.back().q.begin(); claim!=mtlsd_file.back().q.end();++claim)
{
EV_DEBUG << "(" << string(claim->position) << ", " << claim->time << ");" << endl;
}
// The precedent display works correctly
}
else
{
EV_DEBUG << "I already have data about the node " << node->ID << endl;
if (node->q.size() == 3)
{
EV_DEBUG << "I already have three time-location claim in the queue" << endl;
EV_DEBUG << "Here they are: ";
EV_DEBUG << "For node " << (*node).ID << endl;
for(auto fileclaim=(*node).q.begin(); fileclaim!=(*node).q.end();++fileclaim)
EV_DEBUG << "(" << string((*fileclaim).position) << ", " << (*fileclaim).time << ");" << endl;
EV_DEBUG << "I will delete the old one (" << node->q.front().position << ", " << node->q.front().time << ")" << endl;
node->q.pop_front();
}
node->q.push_back(recitem);
EV_DEBUG << "I have pushed this new one : (" << string(node->q.back().position) << ", " << node->q.back().time << ")" << endl;
}
EV_DEBUG << "Here they are all time-location claims in the queue : ";
for(auto fileclaims=node->q.begin(); fileclaims!=node->q.end();++fileclaims)
{
EV_DEBUG << "(" << string(fileclaims->position) << ", " << fileclaims->time << ");" << endl;
}
// The last element is displayed correctly, but those before not.
.
.
.

git_clone error message Assertion failed: git_atomic_get(&git__n_inits) > 0

When I tried to do git_clone() (using libgit2), this error message occured
Assertion failed: git_atomic_get(&git__n_inits) > 0, file C:\data\Install\Git\libgit2-0.25.1\src\global.c, line 199
My program is interrupted by Visual Studio:
R6010 - abort() has been called
There is my code :
git_repository *cloned_repo = NULL;
cout << all_urls.at(num).c_str() << " -> " << clone_to.at(num).c_str() << endl;
int error = git_clone(&cloned_repo, all_urls.at(num).c_str(),clone_to.at(num).c_str(), &clone_opts);
if (error != 0) {
const git_error *err = giterr_last();
cerr << "error in clone num " << num << " -> message :" << err->message << endl;
}
else cout << endl << "Clone " << num << " succesful" << "(from url : " << all_urls.at(num) << " " << "to path : " << clone_to.at(num) << ")" << endl;
git_repository_free(cloned_repo);
I have properly set clone_opts (credentials), so I really do not know where is the problem. I have done git_clone() in different projects before, and I did it this way, but I hadn't had such errors before.
Thanks
I forgot to call the functions git_libgit2_init() and git_libgit2_shutdown() in this method. I called it in previous methods and I thought I don't have to do that also there.

C++ - WinAPI get list of all connected USB devices

I'm trying to create a program that will categorize all the connected USB devices and their port GUID.
I found an example of how to get all the information from connected input devices:
#include <windows.h>
#include <iostream>
// Namespace
using namespace std;
// Main
int main()
{
// Program
cout << "USB Device Lister." << endl;
// Get Number Of Devices
UINT nDevices = 0;
GetRawInputDeviceList(NULL, &nDevices, sizeof(RAWINPUTDEVICELIST));
// Got Any?
if (nDevices < 1)
{
// Exit
cout << "ERR: 0 Devices?";
cin.get();
return 0;
}
// Allocate Memory For Device List
PRAWINPUTDEVICELIST pRawInputDeviceList;
pRawInputDeviceList = new RAWINPUTDEVICELIST[sizeof(RAWINPUTDEVICELIST) * nDevices];
// Got Memory?
if (pRawInputDeviceList == NULL)
{
// Error
cout << "ERR: Could not allocate memory for Device List.";
cin.get();
return 0;
}
// Fill Device List Buffer
int nResult;
nResult = GetRawInputDeviceList(pRawInputDeviceList, &nDevices, sizeof(RAWINPUTDEVICELIST));
// Got Device List?
if (nResult < 0)
{
// Clean Up
delete[] pRawInputDeviceList;
// Error
cout << "ERR: Could not get device list.";
cin.get();
return 0;
}
// Loop Through Device List
for (UINT i = 0; i < nDevices; i++)
{
// Get Character Count For Device Name
UINT nBufferSize = 0;
nResult = GetRawInputDeviceInfo(pRawInputDeviceList[i].hDevice, // Device
RIDI_DEVICENAME, // Get Device Name
NULL, // NO Buff, Want Count!
&nBufferSize); // Char Count Here!
// Got Device Name?
if (nResult < 0)
{
// Error
cout << "ERR: Unable to get Device Name character count.. Moving to next device." << endl << endl;
// Next
continue;
}
// Allocate Memory For Device Name
WCHAR* wcDeviceName = new WCHAR[nBufferSize + 1];
// Got Memory
if (wcDeviceName == NULL)
{
// Error
cout << "ERR: Unable to allocate memory for Device Name.. Moving to next device." << endl << endl;
// Next
continue;
}
// Get Name
nResult = GetRawInputDeviceInfo(pRawInputDeviceList[i].hDevice, // Device
RIDI_DEVICENAME, // Get Device Name
wcDeviceName, // Get Name!
&nBufferSize); // Char Count
// Got Device Name?
if (nResult < 0)
{
// Error
cout << "ERR: Unable to get Device Name.. Moving to next device." << endl << endl;
// Clean Up
delete[] wcDeviceName;
// Next
continue;
}
// Set Device Info & Buffer Size
RID_DEVICE_INFO rdiDeviceInfo;
rdiDeviceInfo.cbSize = sizeof(RID_DEVICE_INFO);
nBufferSize = rdiDeviceInfo.cbSize;
// Get Device Info
nResult = GetRawInputDeviceInfo(pRawInputDeviceList[i].hDevice,
RIDI_DEVICEINFO,
&rdiDeviceInfo,
&nBufferSize);
// Got All Buffer?
if (nResult < 0)
{
// Error
cout << "ERR: Unable to read Device Info.. Moving to next device." << endl << endl;
// Next
continue;
}
// Mouse
if (rdiDeviceInfo.dwType == RIM_TYPEMOUSE)
{
// Current Device
cout << endl << "Displaying device " << i + 1 << " information. (MOUSE)" << endl;
wcout << L"Device Name: " << wcDeviceName << endl;
cout << "Mouse ID: " << rdiDeviceInfo.mouse.dwId << endl;
cout << "Mouse buttons: " << rdiDeviceInfo.mouse.dwNumberOfButtons << endl;
cout << "Mouse sample rate (Data Points): " << rdiDeviceInfo.mouse.dwSampleRate << endl;
if (rdiDeviceInfo.mouse.fHasHorizontalWheel)
{
cout << "Mouse has horizontal wheel" << endl;
}
else
{
cout << "Mouse does not have horizontal wheel" << endl;
}
}
// Keyboard
else if (rdiDeviceInfo.dwType == RIM_TYPEKEYBOARD)
{
// Current Device
cout << endl << "Displaying device " << i + 1 << " information. (KEYBOARD)" << endl;
wcout << L"Device Name: " << wcDeviceName << endl;
cout << "Keyboard mode: " << rdiDeviceInfo.keyboard.dwKeyboardMode << endl;
cout << "Number of function keys: " << rdiDeviceInfo.keyboard.dwNumberOfFunctionKeys << endl;
cout << "Number of indicators: " << rdiDeviceInfo.keyboard.dwNumberOfIndicators << endl;
cout << "Number of keys total: " << rdiDeviceInfo.keyboard.dwNumberOfKeysTotal << endl;
cout << "Type of the keyboard: " << rdiDeviceInfo.keyboard.dwType << endl;
cout << "Subtype of the keyboard: " << rdiDeviceInfo.keyboard.dwSubType << endl;
}
// Some HID
else // (rdi.dwType == RIM_TYPEHID)
{
// Current Device
cout << endl << "Displaying device " << i + 1 << " information. (HID)" << endl;
wcout << L"Device Name: " << wcDeviceName << endl;
cout << "Vendor Id:" << rdiDeviceInfo.hid.dwVendorId << endl;
cout << "Product Id:" << rdiDeviceInfo.hid.dwProductId << endl;
cout << "Version No:" << rdiDeviceInfo.hid.dwVersionNumber << endl;
cout << "Usage for the device: " << rdiDeviceInfo.hid.usUsage << endl;
cout << "Usage Page for the device: " << rdiDeviceInfo.hid.usUsagePage << endl;
}
// Delete Name Memory!
delete[] wcDeviceName;
}
// Clean Up - Free Memory
delete[] pRawInputDeviceList;
// Exit
cout << endl << "Finnished.";
cin.get();
return 0;
}
I tried to convert this code to get all the connected USB devices but failed.
So my question is what is the best way to collect the data I'm looking for?
If you want all USB devices, not just "input" devices, then you need to use the same APIs that Device Manager does.
For example, all devices shown by Device Manager can be listed with the help of the SetupDiGetClassDevs function.
For listing USB devices, you'll want to use the enumerator parameter set to "USB" (the enumerator is the bus where the device is attached, for example it can be "PCI", "PCMCIA", "USB" for the main computer busses, and it can also be a secondary bus provided by an expansion device, e.g. "SCSI", "FTDIBUS", and so on). You may sometimes find that you're more interested in child devices than the USB-attached parent device itself.
Keep in mind that it is not enough just to comment // (rdi.dwType == RIM_TYPEHID) as you did in following sequence, since it will print only rdiDeviceInfo.hid.SOMETHING info. If device is not HID, I would expect some junk, or similar to be printed.
else // (rdi.dwType == RIM_TYPEHID)
{
// Current Device
cout << endl << "Displaying device " << i + 1 << " information. (HID)" << endl;
wcout << L"Device Name: " << wcDeviceName << endl;
cout << "Vendor Id:" << rdiDeviceInfo.hid.dwVendorId << endl;
cout << "Product Id:" << rdiDeviceInfo.hid.dwProductId << endl;
cout << "Version No:" << rdiDeviceInfo.hid.dwVersionNumber << endl;
cout << "Usage for the device: " << rdiDeviceInfo.hid.usUsage << endl;
cout << "Usage Page for the device: " << rdiDeviceInfo.hid.usUsagePage << endl;
}
I would recommend you to add some logging and breakpoints (to print number of devices, to print all device names etc.). If you don't solve it, please paste the code that you use for testing with precise issue explanation.
UPDATE:
GetRawInputDeviceList function
Remarks
The devices returned from this function are the mouse, the keyboard, and other Human Interface Device (HID) devices.
If your device is not HID don't expect to see it in a list.

Printing out std::array with strings not working

I have the following code and it is not printing out to console:
void generateRandomStringArray(array<string, N> &arrayRef)
{
cout << "Generating random string array..." << endl;
for (size_t i = 0; i < N; i++)
{
arrayRef[i] = randomString();
cout << "Value of i = " << i << ": " << stoi(arrayRef[i]) << endl;
cout << arrayRef[i] << endl;
}
cout << "Generating array successful." << endl;
};
The problem is at the line cout << arrayRef[i] << endl; and i get the error, that there is a unhandeld exception, but what is the problem? Why is the exception thrown and how can I correct this?
Exception trace:
First-chance exception at 0x76EFC42D in SortingAlgorithms.exe: Microsoft C++ exception: std::invalid_argument at memory location 0x0344F8EC.
If there is a handler for this exception, the program may be safely continued.
Swap the lines:
cout << "Value of i = " << i << ": " << stoi(arrayRef[i]) << endl;
cout << arrayRef[i] << endl;
to
cout << arrayRef[i] << endl;
cout << "Value of i = " << i << ": " << stoi(arrayRef[i]) << endl;
and You'll see the error is at the stoi call, where you're calling stoi with some broken string.

GetConsoleSelectionInfo C++

cI want to select some text with my cursor using the Mark Function from Console, but my code doesn't work ...
CONSOLE_SELECTION_INFO c;
if(GetConsoleSelectionInfo(&c))
{
while((c.dwFlags & CONSOLE_MOUSE_DOWN) == 0) { if(c.dwFlags) cout << c.dwFlags; }
cout << "SelectionAnchor: " << c.dwSelectionAnchor.X << " " << c.dwSelectionAnchor.Y;
cout << "RectangleSelection: " << c.srSelection.Top << " " << c.srSelection.Left << c.srSelection.Bottom << c.srSelection.Right;
}
else cout << "\n\nError: " << GetLastError();
Whatever I'm selecting or I'm doing, always c.dwFlags will be 0 ...