libspotify: Access violation reading location 0x00000000. (Windows) - c++

So, I try to get a specific playlist via the URI like this:
sp_link *link;
sp_playlist *playlist;
sp_playlist_callbacks playlist_callbacks = { 0 };
link = sp_link_create_from_string("spotify:user:spotify:playlist:2iY4BLINjMOGJX4qHCWNju");
playlist_callbacks.playlist_state_changed = playlist_state_changed;
WaitForSingleObject(lib_lock, INFINITE);
playlist = sp_playlist_create(session, link); // <- Program crashes here
sp_playlist_add_callbacks(playlist, &playlist_callbacks, NULL);
WaitForSingleObject(lib_event_call_finished, INFINITE);
ReleaseMutex(lib_lock);
The callback is the following:
void SP_CALLCONV playlist_state_changed(sp_playlist *playlist, void *user_data)
{
if (sp_playlist_is_loaded(playlist)) {
SetEvent(lib_event_call_finished);
}
}
lib_lock is a mutex (CreateMutex(NULL, FALSE, NULL);)
lib_event_call_finshed is an event (CreateEvent(NULL, FALSE, FALSE, NULL);)
One word about my program's architecture:
I have a thread executing the above commands, which is created in the main function. The main function then executes the main loop:
while (true) {
result = WaitForSingleObject(lib_event_notify, next_timeout);
if (result == WAIT_OBJECT_0 || result == WAIT_TIMEOUT) {
do {
sp_session_process_events(session, &next_timeout);
} while (next_timeout == 0);
} else {
ERR_MSG("WaitForSingleObject has failed");
}
}
lib_event_notify is another event, which is called when notify_main_thread is called.
When the marked line is executed I get following error from Visual Studio:
Unhandled exception at 0x100A5550 (libspotify.dll) in prog.exe:
0xC0000005: Access violation reading location 0x00000000.

Related

Thread does not do anything

I try to use a thread to tell the user the COM port for serial communication he entered was wrong. I have a thread class which tries to establish the connection and a function in my main, that should tell the user.
The compiler does not complain, but my program never enters the function. Maybe anyone can spot the mistake I made.
main.cpp:
WindowsDgpsGUIFrame::WindowsDgpsGUIFrame(wxWindow* parent,wxWindowID id)
{
...
Bind(wxEVT_THREAD, &WindowsDgpsGUIFrame::onConnectionFailed, this, wxID_EXIT);
...
}
void WindowsDgpsGUIFrame::OnButtonStartClick(wxCommandEvent& event)
{
NavigationThread* navigationThread = new NavigationThread(this, m_usedVariables);
m_navigationThread = navigationThread;
wxThreadError err = m_navigationThread->Create();
if(err != wxTHREAD_NO_ERROR)
{
StaticStatusText->Enable();
StaticStatusText->SetLabel("Could not create NavigationThread.");
}
else{
StaticStatusText->SetLabel("Thread created");
}
err = m_navigationThread->Run();
if(err != wxTHREAD_NO_ERROR)
{
StaticStatusText->SetLabel("Could not run thread.");
}
}
void WindowsDgpsGUIFrame::onConnectionFailed(wxThreadEvent& event)
{
StaticConnectionText->SetLabel(event.GetString());
}
thread.cpp:
wxThread::ExitCode NavigationThread::Entry()
{
Serial serial;
int resultGnss = serial.Open(m_gnssPort, STANDARD_BAUDRATE);
wxThreadEvent event(wxEVT_THREAD, wxID_RETRY);
if(resultGnss != 0)
{
event.SetString("Connection to GNSS box not possible. Try with another COM port.");
m_parent->GetEventHandler()->AddPendingEvent(event);
}
else{
event.SetString("Connection successful");
m_parent->GetEventHandler()->AddPendingEvent(event);
}
return 0;
}
The thread gets created and starts running, but even though the event is thrown in the thread the program never reaches onConnectionFailed().

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).

Is __finally supposed to run after EXCEPTION_CONTINUE_SEARCH?

In the following code, the function foo calls itself recursively once. The inner call causes an access violation to be raised. The outer call catches the exception.
#include <windows.h>
#include <stdio.h>
void foo(int cont)
{
__try
{
__try
{
__try
{
if (!cont)
*(int *)0 = 0;
foo(cont - 1);
}
__finally
{
printf("inner finally %d\n", cont);
}
}
__except (!cont? EXCEPTION_CONTINUE_SEARCH: EXCEPTION_EXECUTE_HANDLER)
{
printf("except %d\n", cont);
}
}
__finally
{
printf("outer finally %d\n", cont);
}
}
int main()
{
__try
{
foo(1);
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
printf("main\n");
}
return 0;
}
The expected output here should be
inner finally 0
outer finally 0
inner finally 1
except 1
outer finally 1
However, outer finally 0 is conspicuously missing from the real output. Is this a bug or is there some detail I'm overlooking?
For completeness, happens with VS2015, compiling for x64. Surprisingly it doesn't happen on x86, leading me to believe that it is really a bug.
exist and more simply example (we can remove inner try/finally block:
void foo(int cont)
{
__try
{
__try
{
if (!cont) *(int *)0 = 0;
foo(cont - 1);
}
__except (cont? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
{
printf("except %d\n", cont);
}
}
__finally
{
printf("finally %d\n", cont);
}
}
with output
except 1
finally 1
so finally 0 block not executed. but in not recursive case - no bug:
__try
{
foo(0);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
printf("except\n");
}
output:
finally 0
except
this is bug in next function
EXCEPTION_DISPOSITION
__C_specific_handler (
_In_ PEXCEPTION_RECORD ExceptionRecord,
_In_ PVOID EstablisherFrame,
_Inout_ PCONTEXT ContextRecord,
_Inout_ PDISPATCHER_CONTEXT DispatcherContext
);
old implementation of this function with bug here :
//
// try/except - exception filter (JumpTarget != 0).
// After the exception filter is called, the exception
// handler clause is executed by the call to unwind
// above. Having reached this point in the scan of the
// scope tables, any other termination handlers will
// be outside the scope of the try/except.
//
if (TargetPc == ScopeTable->ScopeRecord[Index].JumpTarget) { // bug
break;
}
if we have latest VC compiler/libraries installed, search for chandler.c (in my install in located at \VC\crt\src\amd64\chandler.c )
and in file can view now next code:
if (TargetPc == ScopeTable->ScopeRecord[Index].JumpTarget
// Terminate only when we are at the Target frame;
// otherwise, continue search for outer finally:
&& IS_TARGET_UNWIND(ExceptionRecord->ExceptionFlags)
) {
break;
}
so additional condition is added IS_TARGET_UNWIND(ExceptionRecord->ExceptionFlags) which fix this bug
__C_specific_handler implemented in different crt libraries (in some case with static link, in some case will be imported from vcruntime*.dll or msvcrt.dll (was forwarded to ntdll.dll)). also ntdll.dll export this function - however in latest win10 builds(14393) it still not fixed

Access violation reading location. Heap corruption. Boost thread

I'm trying to create an multithreaded graphical network application using boost, raknet and irrlicht.
I use one thread that receives messages and another thread to proccess the messages and all the graphical work.
this is the error screen I'm getting
First-chance exception at 0x77183c8d in
NetSystemForVideogamesServerTester.exe: 0xC0000005: Access violation reading location 0x0d99d472
this is the output window information
HEAP[NetSystemForVideogamesServerTester.exe]: HEAP: Free Heap block
da58d10 modified at da58fe0 after it was freed Windows has triggered a
breakpoint in NetSystemForVideogamesServerTester.exe.
This may be due to a corruption of the heap, which indicates a bug in
NetSystemForVideogamesServerTester.exe or any of the DLLs it has
loaded.
This may also be due to the user pressing F12 while
NetSystemForVideogamesServerTester.exe has focus.
The output window may have more diagnostic information.
this is when I launch the thread
void receive()
{
boost::thread(&IConnectionInstance::receiveInThread, this);
}
mutex declaration
boost::mutex mMessagesReceived;
this is the code from the receiving thread
void RakNetConnectionInstance::receiveInThread()
{
Packet* packet;
IMessage* message = NULL;
long time = 0;
while (true)
{
message = NULL;
packet = aPeer->Receive();
while (packet)
{
RakNet::BitStream* dataStream = new RakNet::BitStream(packet->data, packet->length, false);
dataStream->IgnoreBits(sizeof(unsigned char)*8);
switch (packet->data[0])
{
case ID_TIMESTAMP:
{
dataStream->Read(time);
int countMessagesAggregated = 0;
dataStream->Read(countMessagesAggregated);
unsigned char messageType = char();
IBitStream* bitStream = new RakNetBitStream(dataStream);
while(countMessagesAggregated > 0)
{
dataStream->Read(messageType);
switch ((EMESSAGE_TYPE)messageType)
{
case EACTOR_CONTENT_MESSAGE:
message = new CActorContentMessage(aUserDataFactory);
break;
case EWORLD_CONTENT_MESSAGE:
message = new CWorldClientContentMessage(aUserDataFactory);
break;
case EUSER_COMMAND_MESSAGE:
message = new CUserCommandMessage(aEventFactory);
break;
case EPREDICTION_MESSAGE:
message = new CPredictionMessage(aUserDataFactory);
break;
case EPREDICTION_RESPONSE_MESSAGE:
message = new CPredictionResponseMessage(aUserDataFactory);
break;
}
countMessagesAggregated --;
if (messageType >= EUSER_MESSAGE && aCustomReceiver)
{
aCustomReceiver->receiveCustomMessages();
}
if (message)
{
message->readFromBitStream(bitStream);
message->setTimeMS(time);
message->setIPAddress(packet->systemAddress.ToString(false));
message->setPort(packet->systemAddress.port);
mMessagesReceived.lock();
aMessagesReceivedQueue.push(message);
printf("adicionando mensaje a cola en lock\n");
mMessagesReceived.unlock();
message = NULL;
}
}
}
break;
}
if (message)
{
message->setTimeMS(time);
message->setIPAddress(packet->systemAddress.ToString(false));
message->setPort(packet->systemAddress.port);
mMessagesReceived.lock();
aMessagesReceivedQueue.push(message);
mMessagesReceived.unlock();
}
aPeer->DeallocatePacket(packet);
packet = aPeer->Receive();
}
if (RakNet::GetTimeMS() - aBeginTimeSearchServersActives > aWaitTimeServersActives && !aTimeOut)
{
boost::mutex::scoped_lock lock(mTimeOut);
aTimeOut = true;
}
}
}
here I attend the messages from queue in the proccessing thread
void CMessageManager::attendMessages()
{
std::queue<IMessage*> messages = aConnectionInstance->getMessagesReceivedFromQueue();
while(!messages.empty())
{
notifyMessage(messages.back());
aConnectionInstance->popMessageReceivedFromQueue();
messages.pop();
}
}
here I access the message queue
std::queue<IMessage*> RakNetConnectionInstance::getMessagesReceivedFromQueue()
{
boost::mutex::scoped_lock lock(mMessagesReceived);
std::queue<IMessage*> messages;
messages = aMessagesReceivedQueue;
return messages;
}
and finally here I delete the message from queue
void RakNetConnectionInstance::popMessageReceivedFromQueue()
{
boost::mutex::scoped_lock lock(mMessagesReceived);
if (!aMessagesReceivedQueue.empty())
{
aMessagesReceivedQueue.pop();
}
}
I'm new to c++ and multithreading, Please help me, What am I doing wrong?
Thanks in advance.
You don't remove the messages from the original queue, you just copy the pointers to a new queue. So the following happens:
You receive a message. A pointer to it goes on the queue.
You copy the queue, process the message, and delete it.
You receive another message.
You copy the queue. It still contains a pointer to the first message though.
You access the pointer to the first message that you deleted.
This code is broken because it copies the queue leaving the original unmodified:
std::queue<IMessage*> RakNetConnectionInstance::getMessagesReceivedFromQueue()
{
boost::mutex::scoped_lock lock(mMessagesReceived);
std::queue<IMessage*> messages;
messages = aMessagesReceivedQueue;
return messages;
}

runtime error in thread in c++

Getting runtime error in thread, error is "Unhandled exception at 0x0043e98e in clientCheck.exe: 0xC0000005: Access violation reading location 0x025042c4".
//create thread in cpp file
CreateThread(NULL,0,stayConnectedAtClient,this,0,NULL);
//thread definition in header file
static unsigned long __stdcall stayConnectedAtClient(void *i_socketTransPortClient){
((SocketTransportClient*)i_socketTransPortClient)->stayConnectedThread();
return 0;
}
//thread function defination in cpp file
void RMLThinTransport::SocketTransportClient::stayConnectedThread()
{
Sleep(20000);
OutputDebugStringW(L"this is stayconnected thread");
while(m_tryToConnect) // get error here, not getting value of m_tryToConnect it is Boolean and declared in class.
{
if(!m_isConnected) // m_isConnected value is also not updated even if it is changed by other function
{
break;
}
/* sleep for period of time given in configuration file */
Sleep(m_stayConnected);
if(!m_allreadyConnected)
{
bool isConnect=Connect();
if(isConnect)
{
m_allreadyConnected=true;
}
OutputDebugStringW(L"isConnect false");
}
}
}
all values are updated in method disconnect.
bool RMLThinTransport::SocketTransportClient::disconnect()
{
m_isConnected=false;
m_tryToConnect=false;
notifyUserConnected(m_isConnected);
if(m_socketClient!=INVALID_SOCKET)
{
shutdown(m_socketClient,SD_BOTH);
closesocket(m_socketClient);
m_socketClient=INVALID_SOCKET;
}
Sleep(3000);
return false;
}
bool RMLThinTransport::SocketTransportClient::Connect()
{
try
{
m_socketClient = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
if(m_socketClient==INVALID_SOCKET){
int lastError;
lastError=WSAGetLastError();
SocketExceptions exceptionInOpenSocket;
exceptionInOpenSocket.detectErrorOpenSocket(&lastError);
throw exceptionInOpenSocket;
}
}
catch(SocketExceptions& i_exceptionInOpenSocket)
{
throw i_exceptionInOpenSocket;
return false;
}
memset(&m_SocketAddressIn,0,sizeof(m_SocketAddressIn));
m_SocketAddressIn.sin_family=AF_INET;
m_SocketAddressIn.sin_addr.s_addr=inet_addr(m_ccIPAddress);
m_SocketAddressIn.sin_port=htons(m_portNumber);
try
{
if(SOCKET_ERROR==connect(m_socketClient,(SOCKADDR *)&m_SocketAddressIn,sizeof(m_SocketAddressIn)))
{
m_allreadyConnected=false;
int lastErrorCode=WSAGetLastError();
SocketExceptions exceptionInConnection;
exceptionInConnection.detectErrorConnect(&lastErrorCode);
throw exceptionInConnection;
}
else
{
setConnected(true);
m_allreadyConnected=true;
if(m_evesdropString!=""){
char* charbuf=new char[m_evesdropString.size()+1];
std::copy(m_evesdropString.begin(),m_evesdropString.end(),charbuf);
charbuf[m_evesdropString.size()]='\0';
int iResult=send(m_socketClient,charbuf,strlen(charbuf),0);
memset(charbuf,0x00,sizeof(charbuf));
}
CreateThread(NULL,0,receiveClientData,this,0,NULL);
return true;
}
}
catch(SocketExceptions& i_exceptionInConnection)
{
shutdown(m_socketClient,SD_BOTH);
closesocket(m_socketClient);
m_socketClient=INVALID_SOCKET;
this->exceptionOccurred(EST_EXCEPTIONINCONNECT);
return false;
}
return true;
}
so please can anyone tell me what is the problem.?
It is not a good idea to use CreateThread() directly from C++ code. You should rather use _beginthreadex() to initialize C++ runtime environment for you thread (TLS variables and other stuff).