How to solve "Access violating reading location error" in c++? - c++

Goodday all,
I'm getting the following error:
First-chance exception at 0x67887AB7 (SDL2_mixer.dll) in Racing.exe: 0xC0000005: Access violation reading location 0xCCCCCCD4.
I think the problem could be with the pointer, but I'm not experienced enough in c++ to find it.
I'm hoping someone can tell me what I did wrong, and hopefully I can learn from it :)
Trying to call it from my gamebus.
Music Mus;
Mus.SpeelGeluid("crash");
Music class
bool Music::LoadMusic(){
//Load music
Mix_Music *gMusic = NULL;
gMusic = Mix_LoadMUS("MusicTest.wav");
Mix_PlayMusic(gMusic, -1);
bool success = true;
if (gMusic == NULL)
{
printf("Failed to load Music background song! SDL_mixer Error: %s\n", Mix_GetError());
success = false;
}
// Load sound effects
Mix_Chunk *gCrash = NULL;
gCrash = Mix_LoadWAV("Crash.wav");
if (gCrash == NULL)
{
printf("Failed to load scratch sound effect! SDL_mixer Error: %s\n", Mix_GetError());
success = false;
}
return success;
}
void Music::SpeelGeluid(string soundname){
cout << soundname << endl;
if (soundname == "crash")
{
try
{
Mix_PlayChannel(-1, gCrash, 0);
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e << '\n';
}
}
else
{
} }
Thank you for your time

You have two major problems:
First, you're using gMusic before checking whether it's NULL.
This may crash Mix_PlayMusic, and actually means that compilers may optimise out the later NULL check.
Second, and most likely the cause of your problem, you're declaring gCrash and gMusic as local variables in LoadMusic.
From the names, and your use of gCrash in SpeelGeluid, my educated guess is that you also have two global variables, or possibly member variables, with the same names where you intend to store the results of loading the files.
Your local variables are hiding these globals, and you're only modifying the local variables.
Remove the lines
Mix_Music *gMusic = NULL;
and
Mix_Chunk *gCrash = NULL;
to get rid of these local variables.
And do initialise the globals to NULL when you define them.

Check your pointers as soon as you've allocated them and handle them appropriately. You nearly do:
gMusic = Mix_LoadMUS("MusicTest.wav");
Mix_PlayMusic(gMusic, -1); // <- You're using the pointer here before you check it
bool success = true;
if (gMusic == NULL) // <- this needs to be immediately after assignment
That's just from the code you've pointed. It's also possible you've missed a generic initialisation call from the SDL2_mixer.dll.
Do debug it and step through line by line so you know which bit is causing the error.

Related

FILE * creation error: Unhandled exception (ucrtbased.dll) Access violation reading location

I'm working with a simple fopen, fwrite, fflush, fclose body of code. For some reason, however, every time I try to create a FILE * object, it crashes. My code is below.
//fopen
FILE * f_data = fopen("out.txt", 'wb'); // BREAKS HERE
if (f_data == NULL) { printf("fopen failed!"); }
//fwrite
int fwritten = fwrite(data, 1, content_length, f_data);
if (fwritten == 0) { printf("fwrite failed!"); }
//fflush
int flush = fflush(f_data);
if (flush != 0) { printf("fflush failed!"); }
//fclose
int close = fclose(f_data);
if (close != 0) { printf("fclose failed!"); }
Whenever I run this code, I get the following error:
Unhandled exception at 0x5F52C795 (ucrtbased.dll) in main.exe: 0xC0000005: Access violation reading location 0x00007762.
I've been researching this problem for about an hour now, to no avail. I've learned that this is Windows telling me I've encountered a segmentation fault, possibly from trying to dereference a NULL pointer.
If anybody has some insight on why my File * instantiation won't work, please share!
EDIT: I'm not sure it's relevant to this question but the data buffer being written is a simple string: "Hello, world, and all who inhabit it!" and content_length is set to sizeof(data).

Why can't webrtc find the capturer it suggested?

I'm creating a webrtc-based voip app for windows in C++. I'm trying to initialize a peerconnection. I'm stuck at the part to fetch a camera. I'm using the following code to find a camera to start streaming media from (copied from the peerconnection client example):
rtc::scoped_ptr<cricket::DeviceManagerInterface> dev_manager(cricket::DeviceManagerFactory::Create());
if (!dev_manager->Init()) {
LOG(LS_ERROR) << "Can't create device manager";
return NULL;
}
std::vector<cricket::Device> devs;
if (!dev_manager->GetVideoCaptureDevices(&devs)) {
LOG(LS_ERROR) << "Can't enumerate video devices";
return NULL;
}
std::vector<cricket::Device>::iterator dev_it = devs.begin();
cricket::VideoCapturer* capturer = NULL;
for (; dev_it != devs.end(); ++dev_it) {
capturer = dev_manager->CreateVideoCapturer(*dev_it);
if (capturer != NULL)
break;
}
capturer is empty after this procedure. I stepped through the code to see what was wrong. dev_manager is succesfully intialized, devs gets a single entry (my webcam) with a name:
"logitech HD webcam c270"
And an id:
"\\\\?\\usb#vid_046d&pid_0825&mi_00#7&2dbd1a82&1&0000#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\\{bbefb6c7-2fc4-4139-bb8b-a58bba724083}"
But after the CreateVideoCapturer() call, capturer is still empty. I get a warning in the console saying:
Warning(webrtcvideocapturer.cc:175): Failed to find capturer for id: \\?\usb#vid_046d&pid_0825&mi_00#7&2dbd1a82&1&0000#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\{bbefb6c7-2fc4-4139-bb8b-a58bba724083}
I checked if the id I get in devs and this one match and they do. The entire log for my app can be found in this pastebin. As you can see, right after trying to assign the camera as capturer and failing, the app crashes on an assert(capturer != NULL) call somewhere in videosource.cc.
The camera is not in use, nor is it defect. The peerconnection client example works perfectly and uses the same code. I think I'm missing some step in the initialization of webrtc, but I can't find which step.
edit with additional info
I'm debug stepping through the library now. In webrtcvideocapturer.cc around line 160 is the following code:
int num_cams = info->NumberOfDevices();
char vcm_id[256] = "";
bool found = false;
for (int index = 0; index < num_cams; ++index) {
char vcm_name[256];
int32 i = info->GetDeviceName(index, vcm_name, ARRAY_SIZE(vcm_name), vcm_id, ARRAY_SIZE(vcm_id));
if (i != -1) {
if (device.name == reinterpret_cast<char*>(vcm_name)) {
found = true;
break;
}
}
}
if (!found) {
LOG(LS_WARNING) << "Failed to find capturer for id: " << device.id;
factory_->DestroyDeviceInfo(info);
return false;
}
There are two problems with this part. First of all, if I step into info->NumberOfDevices() it shows me that that function's only content is the line return 0;. I tried hard-coding 1 there, to at least get into the for loop. Then when I step into the info->GetDeviceName() call it shows me that the content of that function is return -1;.
These two functions are meant to be implemented by a class that inherits from webrtc::VideoCaptureModule::DeviceInfo, so there is clearly something not initialized that does needs to be initialized. What do I still need to do before trying to get a camera?
What libraries did you link?
Because Google WebRTC source codes are changing rapidly, it is difficult to track down issues to the source level.
But I remember the almost same problem occurred when I accidentally linked external capture module library (video_capture_module_impl ??) or (I'm not sure) omitted internal impl (video_capture_module_internal_impl ??).

FreeLibrary() Access Violation

Follwing Code should scan a directory with .dll for Plugin containers. If it encounters a non-Container .dll, it crashes at the given location with an Access Violation Exception
(Execution at 0x00000000). I am pretty sure that this is not a overflow error or similar because it is freed right after being loaded. I can guarantee there is not a single call of the dll's function. Only the GetProcAddress trying to figure out my entry point to the Plugin discovery.
What else can go wrong here? Could it be that im freeing a module that one of my plugin-dll's is internally linking to? If so, how could I detect this is the case, and opt for not calling FreeLibrary in this case?
string filePathStr (path);
string fileSearchKey = filePathStr + "\\*.dll";
WIN32_FIND_DATAA fd;
HMODULE hmod;
bool bFirstRun = true;
bool bFinishedRun = false;
HANDLE h = INVALID_HANDLE_VALUE;
printf("\r\n");
while (!bFinishedRun)
{
if (bFirstRun)
{
h = FindFirstFileA(fileSearchKey.c_str(), &fd);
bFirstRun = false;
} else
{
if (FindNextFileA(h, &fd) == FALSE) bFinishedRun = true;
}
if (!SetDllDirectoryA(filePathStr.c_str())) break;
hmod = LoadLibraryA(fd.cFileName);
if (!hmod) continue;
rpiRegisterPluginsCall prpiRegisterPlugins = reinterpret_cast<rpiRegisterPluginsCall>(GetProcAddress(hmod, "_rpiRegisterPlugins#4"));
if (prpiRegisterPlugins == NULL)
{
FreeLibrary(hmod); // Access violation
continue;
}
if (prpiRegisterPlugins(this) != 0)
{
FreeLibrary(hmod);
continue;
}
m_loaded.push_back((unsigned long long)hmod);
}
Edit:
Apparently there is only one offending .dll in many non-containers (deleted that one and it works). So I am opting for the explanation that something goes wrong in dllmain.

"Access violation writing location" with file.getline? (Only in release build)

getting this error in an application written in C++ (VS 2010):
Unhandled exception at 0x77648da9 in divt.exe: 0xC0000005: Access
violation writing location 0x00000014.
it points to this function in free.c:
void __cdecl _free_base (void * pBlock)
{
int retval = 0;
if (pBlock == NULL)
return;
RTCCALLBACK(_RTC_Free_hook, (pBlock, 0));
retval = HeapFree(_crtheap, 0, pBlock);
if (retval == 0) //<-----------------------right here
{
errno = _get_errno_from_oserr(GetLastError());
}
}
Via debugging I was able to determine where its actually crashing:
void MenuState::LoadContentFromFile(char* File,std::string &Content)
{
std::string strbuf;
char buffer[1028];
std::fstream file;
file.open(File,std::ios_base::in);
if(file.fail())
{
Content = ErrorTable->GetString("W0001");
return;
}
if(file.is_open())
{
while(!file.eof())
{
file.getline(buffer,128,'\n'); // <----here
strbuf = buffer;
Content += strbuf + "\n";
}
}
file.close();
strbuf.clear();
}
It crashes on file.getline(buffer,128,'\n');
I don't understand why but it's only doing it in release build (Optimizations turned off), on debug build its working fine.
Any Ideas?
I know this is an old question, but when you encounter these sorts of issues buried deep in files such as, free.c or xmemory, you may also want to double check your project configuration. Especially when the issue pertains to only certain build configurations.
For example, in MSVC check your Project Properties > Configuration Properties > C/C++ > Code Generation > Runtime Library. Make sure it consistent for all dependencies and that it is set to a Debug/Release variant depending on the current build.
I would bet that the read prior to the read crashing the application actually failed (although I'm not quite sure why it would crash). The important thing to note is that eof() is only good for determining what caused a read failure (and typically suppressing an error message). In addition, you always want to check after the read whether it was successful. Finally, I can't see any reason why you don't read an std::string directly. In summary, try to use this loop instead:
for (std::string strbuf; std::getline(file, strbuf); ) {
Content += strbuf;
}
Asked a friend for help, we came up with this Solution:
std::string strbuf;
char buffer[256] = "\0";
FILE* f = fopen(File, "rt");
while(fgets(buffer,sizeof(buffer),f) != NULL)
{
Content += buffer;
}
fclose(f);
strbuf.clear();
Works fine, still thanks for your efforts.

Crash when connecting to Bluetooth device via WinAPI Socket (Access violation reading location 0x00000004)

I think you are my last hope. I have got here a Bluetooth device (it is a sensor to be more precisely) which I want to connect to and read data from. The device offers SPP (Serial Port Profile). To avoid the problem of reliable mapping from Bluetooth addresses and virtual serial ports (COM Ports), I am going to use sockets.
Unfortunately the application always crashes before returning from WinAPI function connect(...) with: 0xC0000005: Access violation reading location 0x00000004, so I get no error code.
BUT, and that is weird, when I right-click on the Bluetooth System Tray Icon to to show available devices, my device shows up being authenticated and connected. This list was empty before, of course.
My OS is Windows 7 64 Bit, the IDE is Visual Studio 2010, Microsoft Bluetooth Stack. Code to find and connect to my only device:
#include <iostream>
#include <string>
#include <algorithm>
#include <cassert>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <BluetoothAPIs.h>
#include <Winsock2.h>
#include <Ws2bth.h>
BOOL auth_callback_ex(LPVOID pvParam, PBLUETOOTH_AUTHENTICATION_CALLBACK_PARAMS authParams)
{
BLUETOOTH_AUTHENTICATE_RESPONSE response;
response.bthAddressRemote = authParams->deviceInfo.Address;
response.authMethod = authParams->authenticationMethod; // == BLUETOOTH_AUTHENTICATION_METHOD_LEGACY
UCHAR pin[] = "1234";
std::copy(pin, pin+sizeof(pin), response.pinInfo.pin);
response.pinInfo.pinLength = sizeof(pin)-1; //excluding '\0'
response.negativeResponse = false;
HRESULT err = BluetoothSendAuthenticationResponseEx(NULL, &response);
if (err)
{
std::cout << "BluetoothSendAuthenticationResponseEx error = " << err << std::endl;
}
return true;
}
int main()
{
BLUETOOTH_DEVICE_SEARCH_PARAMS btSearchParams;
btSearchParams.dwSize = sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS);
btSearchParams.cTimeoutMultiplier = 5; //5*1.28s search timeout
btSearchParams.fIssueInquiry = true; //new inquiry
//return all known and unknown devices
btSearchParams.fReturnAuthenticated = true;
btSearchParams.fReturnConnected = true;
btSearchParams.fReturnRemembered = true;
btSearchParams.fReturnUnknown = true;
btSearchParams.hRadio = NULL; //search on all local radios
BLUETOOTH_DEVICE_INFO btDeviceInfo;
ZeroMemory(&btDeviceInfo, sizeof(BLUETOOTH_DEVICE_INFO)); //"initialize"
btDeviceInfo.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
HBLUETOOTH_DEVICE_FIND btDeviceFindHandle = NULL;
btDeviceFindHandle = BluetoothFindFirstDevice(&btSearchParams, &btDeviceInfo);
if(btDeviceFindHandle)
{
HBLUETOOTH_AUTHENTICATION_REGISTRATION authCallbackHandle = NULL;
DWORD err = BluetoothRegisterForAuthenticationEx(&btDeviceInfo, &authCallbackHandle, &auth_callback_ex, NULL);
if (err != ERROR_SUCCESS)
{
DWORD err = GetLastError();
std::cout << "BluetoothRegisterForAuthentication Error" << err << std::endl;
}
/////////////// Socket
WSADATA wsaData;
err = WSAStartup(MAKEWORD(2,2), &wsaData);
if (err)
{
std::cout << "WSAStartup error = " << err << std::endl;
}
// create BT socket
SOCKET s = socket (AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
assert(s != INVALID_SOCKET); //WSAGetLastError //throw // runtime check release?
SOCKADDR_BTH btSockAddr;
btSockAddr.addressFamily = AF_BTH;
btSockAddr.btAddr = btDeviceInfo.Address.ullLong;
btSockAddr.serviceClassId = RFCOMM_PROTOCOL_UUID; //SerialPortServiceClass_UUID (no difference)
btSockAddr.port = BT_PORT_ANY;
err = connect(s, reinterpret_cast<SOCKADDR*>(&btSockAddr), sizeof(SOCKADDR_BTH));
/* <--- never got so far --> */
if (err)
{
DWORD wsaErr = WSAGetLastError();
std::cout << "connect error = " << wsaErr << std::endl;
}
else
{
//err = shutdown(s, SD_BOTH);
err = closesocket(s);
if (err)
{
std::cout << "closesocket error = " << err << std::endl;
}
}
WSACleanup();
///////////////Socket
BOOL ok = BluetoothUnregisterAuthentication(authCallbackHandle);
if (!ok)
{
DWORD err = GetLastError();
std::cout << "BluetoothUnregisterAuthentication Error" << err << std::endl;
}
ok = BluetoothFindDeviceClose(btDeviceFindHandle);
if (!ok)
{
DWORD err = GetLastError();
std::cout << "BluetoothDeviceClose Error" << err << std::endl;
}
}
else
{
DWORD err = GetLastError();
std::cout << "BluetoothFindFirstDevice Error" << err << std::endl;
}
std::cin.get();
}
I have made some few more observations:
The authentication callback and the BluetoothSendAuthenticationResponseEx function are working fine, there is no error given back.
If I do not install the authentication callback (BluetoothRegisterForAuthenticationEx) and therefore have to manually enter the PIN (the UI shows up automatically while trying to connect), connect function returns properly and everything works fine, too. I even got data (the recv part is omitted in this snippet).
If I search and pair completely manually (Bluetooth Tray Icon -> Add Device), everything is fine, too. A service and a virtual serial port is installed. Data come via putty.
So somewhere between calling the authentication callback and end of the connect function something is going wrong. Maybe when trying to get a certain structure data via a pointer, which should not be NULL, plus offset.
Or am I doing something wrong? Is there something missing?
Thanks...
The problem is that your function is using the wrong calling convention. According to MSDN, you need to use the CALLBACK macro, as in:
BOOL CALLBACK auth_callback_ex(LPVOID pvParam, PBLUETOOTH_AUTHENTICATION_CALLBACK_PARAMS authParams)
Having the wrong calling convention will result in a stack mismatch on return, which could cause an access violation inside the MS Bluetooth code when it can't find its local variables.
Or it could result in the parameters to your function being all jumbled. If authParams and pvParam are swapped, because the cdecl calling convention expects args pushed from right to left and stdcall pushes them left to right, you'd get NULL in authParams, and then authParams->deviceInfo.Address will try to read address 0x04.
The compiler should have caught this. Compile with maximum warnings turned on (/W4). You'll have to ignore the warnings about unknown pragma, this is a bug in the header which I'm reporting to Microsoft (misspelled #pragma deprecated).
Unfortunately there's a second bug in the header, much more serious, of not specifying the calling convention explicitly, with the result that it will only work correctly on x86 (32-bit code) if /Gz is used. Yuck!
Followup: In the SDK headers shipped with VS2013, both issues are fixed.
You have a null-pointer access somewhere. "Access violation reading location 0x00000004" indicates that, as it is only 4 bytes away from zero.
I have a couple of thoughts to share with you, but be advised that these are hunches. I haven't compiled and debugged your code, although I commend you for posting a complete sample.
I think the crash may be within your authentication callback function, due to a '''NULL''' pointer dereference.
These lines:
response.bthAddressRemote = authParams->deviceInfo.Address;
response.authMethod = authParams->authenticationMethod; // == BLUETOOTH_AUTHENTICATION_METHOD_LEGACY
will cause the message you describe, if you are running on 32-bit Windows, and '''authParams''' may be '''NULL''' -- in that case, '''deviceInfo''' contributes a zero offset (it is at the beginning of the '''BLUETOOTH_AUTHENTICATION_CALLBACK_PARAMS'''), and '''.Address''' does contribute an offset of 4 ('''NULL + 4 == 0x00000004'''), because it follows a '''DWORD''' and nothing else within the '''BLUETOOTH_DEVICE_INFO''' layout.
Is it possible that '''authParams''' is NULL when your callback is called?
As another poster has already mentioned, this could be due to incorrect calling convention (lack of '''CALLBACK''' macro) -- causing otherwise correct parameters to mis-align with the positions the compiled code is reading.
The second thought was:
BLUETOOTH_DEVICE_INFO btDeviceInfo;
ZeroMemory(&btDeviceInfo, sizeof(BLUETOOTH_DEVICE_INFO)); //"initialize"
btDeviceInfo.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
Can be represented by:
BLUETOOTH_DEVICE_INFO btDeviceInfo = {sizeof(BLUETOOTH_DEVICE_INFO)};
According to the standard, this will zero the other fields of '''btDeviceInfo'''.
Or write managed code and use my Bluetooth library 32feet.NET Super simple. http://32feet.codeplex.com/
Will it crash then -- if so there's something wrong on your PC...