Visual Studio has triggered a breakpoint - c++

It seems the breakpoint is due to heap corruption.
Here's a snapshot of two frames from the call stack:
First:
void QString::free(Data *d)
{
#ifdef QT3_SUPPORT
if (d->asciiCache) {
QMutexLocker locker(asciiCacheMutex());
Q_ASSERT(asciiCache);
asciiCache->remove(d);
}
#endif
qFree(d);//Breakpoint here, d = 0x08c9efd4
}
Second:
void qFree(void *ptr)
{
::free(ptr); //Breakpoint here, ptr = 0x00000000
}
What makes me confused is the pointer is 0x08c9efd4 before it is passed to qFree and suddenly becomes NULL when it is passed to qFree.
What may cause the sudden change of the pointer ?

Related

Mysterious C++ threading crash

The following code strangely crashes when entering the run function. None of the printfs trigger, and single-stepping into the function will cause a crash. Is it undefined behaviour, or a compiler bug? I'm on MacOS compiling with Apple clang 12.0.0. It crashes with EXC_BAD_ACCESS (code = 2).
#include <iostream>
#include <thread>
#include <vector>
struct Chunk {
// the array must be this big
// other array sizes don't trigger the bug consistently
uint8_t array[524288];
};
std::thread generator_thread;
std::mutex generator_lock;
std::vector<Chunk*> to_generate;
std::condition_variable data_ready;
std::atomic<bool> running;
void begin();
void run();
void begin() {
running = true;
auto func = [] {
run();
};
generator_thread = std::thread(func);
}
void run() {
printf("Running in generator\n");
while (running) {
printf("Running in loop\n");
Chunk *task;
// take a chunk from the queue
{
std::unique_lock<std::mutex> lock(generator_lock);
data_ready.wait(lock, [] { return to_generate.size() > 0 || !running; });
if (!running) break;
task = to_generate.back();
to_generate.pop_back();
}
printf("deref chunk\n");
// Despite never being executed in this example, this line merely existing
// will cause a crash when entering the run_generator function.
Chunk chunk = *task;
// *task.chunk;
// ^^^ Only having the line above will not trigger the bug; it must be assigned
}
}
int main(int argc, const char *argv[]) {
begin();
while (true) {
printf("run\n");
}
return 0;
}
So, when you change your function to pre-reserve a stack frame with space for a half-megabyte object ... it crashes right at the start of the function when setting up that stack frame?
That's probably because you made sizeof Chunk equal to the entire default OSX thread stack size of 512Kb. If you single-step into the function, you should be able to see the instruction that triggers the fault, and it will likely be part of the stack frame setup/function preamble.
All of this is implementation-specific (the stack frames, the per-thread stack size), but putting really big things on the stack is generally a bad idea.

Object in stack of `main` function is overwritten when first task runs (FreeRTOS)

I try to explain my problem with a simple example
typedef function<bool()> TaskCallback;
class Task
{
public:
Task(TaskCallback task_callback) : task_callback(task_callback)
{
long_string_test = "This is a long string 0123456789ABCDEF 0123456789ABCDEF 0123456789ABCDEF";
xTaskCreate(Task::RunTask, "task_name", 2560, this, 3, &task_handle);
}
~Task()
{
while(1); //Breakpoint: The destructor is never called
}
private:
static void RunTask(void* params)
{
Task* _this = static_cast<Task*>(params);
_this->task_callback(); //The program crashes here because task_callback doesn't exist
}
string long_string_test;
TaskCallback task_callback;
TaskHandle_t task_handle;
};
main.cpp
static bool Init_task() { }
void main()
{
Task task(Init_task);
vTaskStartScheduler();
//We should never get here as control is now taken by the FreeRTOS scheduler
while(1);
}
If I check the value of the string long_string_test through the debbuger in the RunTask function I find that it has a strange value, as if the string had been destroyed.
But the destructor of Task class was never called.
If I change the "main.cpp" as below the program works correctly, I think the compiler does some sort of optimization:
static bool Init_task() { }
Task task(Init_task);
void main()
{
vTaskStartScheduler();
//We should never get here as control is now taken by the FreeRTOS scheduler
while(1);
}
p.s. obviously compiler optimizations are disabled
As part of the vTaskStartScheduler call, prvPortStartFirstTask will reset the stack pointer. I can imagine that this will eventually cause other code to overwrite parts of the Task object on the discarded stack space allocated for main. You could set a data breakpoint with the debugger, but I would consider the main stack space trashed when the first task starts.
I think the best solution here is indeed to allocate the Task object statically or possibly with a heap allocation (if your system allows it).
#Botje You're right I changed my example to verify what you said.
main.cpp
int* test;
static void RunTask(void* params)
{
Print(*test); //The "test" pointer has a random value
}
void main()
{
int temp = 9999;
test = &temp;
xTaskCreate(RunTask, "task_name", 2560, NULL, 3, NULL);
vTaskStartScheduler(); //It seems that FreeRTOS clears the main() stack
//We should never get here as control is now taken by the FreeRTOS scheduler
while(1);
}

if(mySharedPtr) causes Signal 11?

Somehow, accessing a shared_ptr without dereferencing it is causing a Signal 11 (SIGSEGV) on Android.
I have a run() function in A that acquires a lock for it's instance of B and calls B::top(). There is only one instance of A. A has other public methods that other threads might call to modify mB (thus the mutex), but they are not being called by anything yet.
LogCat Error:
04-17 15:15:16.903: A/libc(11591): Fatal signal 11 (SIGSEGV) at 0x00000024 (code=1)
In class A:
std::thread mControllerThread;
std::mutex mBMutex;
shared_ptr<B> mB;
A() {
mB.reset( new B() );
mControllerThread = std::thread( std::bind(&A::run, this) );
}
//...
void run() {
std::unique_lock<std::mutex > lk(mBMutex);
shared_ptr<const Event> event = mB->top(B::Scope::FUTURE);
}
In class B:
shared_ptr<EventHeap> mFuture;
B() {
mFuture.reset( new EventHeap() );
}
//...
shared_ptr<const Event> top(Scope scope, int mask=EVENT_MASK_SUPPORTED) const {
shared_ptr<const Event> event;
if(scope == Scope::PAST) {
//...
} else if(scope == Scope::FUTURE) {
LOGD(LOG_TAG, "Testing mFuture ptr");
// Fails here with any of these versions
if(mFuture) {
// if(mFuture.get() != NULL) {
// if(mFuture != nullptr) {
LOGD(LOG_TAG, "Getting top from FUTURE");
event = mFuture->top(mask);
} else {
LOGE(LOG_TAG, "mFuture is null");
}
}
return event;
}
So how can accessing a smart pointer without dereferencing it possibly cause a segfault? Thanks!
The statement you point test if the shared_ptr is initialized with a non-null pointer.
if(mFuture) // can be seen as if(mFuture.privateMember_Ptr != nullptr)
It is pretty clear that the pointer itself is not dereferenced, but the value of the pointer is accessed. So this memory location seems invalid. Now where is this memory location? It is part of mFuture which is itself part of B. Let's rewrite the mFuture to show what we really dereference:
if(this->mFuture.privateMember_Ptr != nullptr)
It seems that "this" is invalid, you can start by printing it in the top method, and "unwind" the stack with the same debugging. Looking at the source, "this" should correspond to mB in class A. So you can print mB in A::run() before calling B::top().
mB is initialized in A's ctor with a "new B()". Do you check somewhere that this memory allocation succeed? (exceptions are disabled by default on Android AFAIK, so new can return nullptr)

How to find a way to detect the memory leak in this code?

All, Could any one tell me a good way or tool to detect the memory leak in visual studio for these code? I have tested the crt debug, but while i abort the debug process(shift+f5), the memory leak report doesnot appear in the debug windows.
void fun1()
{
int * pInt = new int;
return;
}
void Execute(void)
{
while(true)
{
cout<<"I will sleep for 1 second..."<<endl;
::Sleep(1000);
fun1();
}
return;
}
int main()
{
Execute();
return 0;
}
Could any one know how to find the memory for above code?
BTW, if i choose to use shared_ptr, the memory leak will not happen again, Right?
The problem here is fairly simple: when you abort a process, leaking memory is more or less taken for granted -- even if your code wouldn't normally leak, aborting it with the debugger is (short of extremely good luck) going to leak memory anyway. As such, most tools that would normally report memory leaks won't when you abort the program with the debugger.
As such, to see a leak report, you just about need to write code that will, at some point, exit on its own instead of requiring you to kill it with the debugger. If you change your code to something like this:
void fun1()
{
int * pInt = new int;
return;
}
void Execute(void)
{
for (int i=0; i<100000; i++)
{
//cout<<"I will sleep for 1 second..."<<endl;
//::Sleep(2000);
fun1();
}
return;
}
int main()
{
Execute();
return 0;
}
By the way, when you pass 2000 as the parameter to Sleep, you should expect it to sleep at least 2 seconds, not just one. For the moment, I've commented out the cout and Sleep, so it should just quickly leak the memory and produce a leak report. With a lot of output and Sleeping, it would do the same, just a lot more slowly and noisily.
Does adding this to the top of your main function not work?
#if defined(DEBUG) | defined (_DEBUG)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
You have to run in debug mode.
The problem is that while a process is running it is hard for an automated process to tell what memory was leaked. In languages that keep track of references to objects and memory blocks you can do this at any time, you just need to find the blocks that have no references. In C/C++ there is no such thing (unless you implement it yourself, that is), so you can't really tell if a memory block has been leaked or not.
One thing you can do in cases like this is to trigger the function that dumps memory leaks at a point in time in the life of your process that you know should not have any leaks. For example, let's say that you know that your application should not have any leaks at the end of each iteration in the Execute() while loop. Then you could do something like this:
#include <crtdbg.h>
void fun1()
{
int * pInt = new int;
return;
}
void Execute(void)
{
int i = 0;
while(true)
{
cout<<"I will sleep for 1 second..."<<endl;
::Sleep(2000);
fun1();
#ifdef _DEBUG
// dump any leaks every 100 iterations
if (++i % 100 == 0)
_CrtDumpMemoryLeaks();
#endif
}
return;
}
int main()
{
Execute();
return 0;
}
See this page for information about _CrtDumpMemoryLeaks() and other functions of the MSVC CRT library.
I hope this helps.
I have no idea about VS, on Linux I'd use valgrind.

How to get pointer from another thread?

Let's have the following class definition:
CThread::CThread ()
{
this->hThread = NULL;
this->hThreadId = 0;
this->hMainThread = ::GetCurrentThread ();
this->hMainThreadId = ::GetCurrentThreadId ();
this->Timeout = 2000; //milliseconds
}
CThread::~CThread ()
{
//waiting for the thread to terminate
if (this->hThread) {
if (::WaitForSingleObject (this->hThread, this->Timeout) == WAIT_TIMEOUT)
::TerminateThread (this->hThread, 1);
::CloseHandle (this->hThread);
}
}
//*********************************************************
//working method
//*********************************************************
unsigned long CThread::Process (void* parameter)
{
//a mechanism for terminating thread should be implemented
//not allowing the method to be run from the main thread
if (::GetCurrentThreadId () == this->hMainThreadId)
return 0;
else {
m_pMyPointer = new MyClass(...);
// my class successfully works here in another thread
return 0;
}
}
//*********************************************************
//creates the thread
//*********************************************************
bool CThread::CreateThread ()
{
if (!this->IsCreated ()) {
param* this_param = new param;
this_param->pThread = this;
this->hThread = ::CreateThread (NULL, 0, (unsigned long (__stdcall *)(void *))this->runProcess, (void *)(this_param), 0, &this->hThreadId);
return this->hThread ? true : false;
}
return false;
}
//*********************************************************
//creates the thread
//*********************************************************
int CThread::runProcess (void* Param)
{
CThread* thread;
thread = (CThread*)((param*)Param)->pThread;
delete ((param*)Param);
return thread->Process (0);
}
MyClass* CThread::getMyPointer() {
return m_pMyPointer;
}
In the main program, we have the following:
void main(void) {
CThread thread;
thread.CreateThread();
MyClass* myPointer = thread.getMyPointer();
myPointer->someMethod(); // CRASH, BOOM, BANG!!!!
}
At the moment the myPointer is used ( in the main thread ) it crashes. I don't know how to get the pointer, which points to memory, allocated in another thread. Is this actually possible?
The memory space for your application is accessible to all threads. By default any variable is visible to any thread regardless of context (the only exception would be variables declared __delcspec(thread) )
You are getting a crash due to a race condition. The thread you just created hasn't started running yet at the point where you call getMyPointer. You need to add some kind of synchronization between the newly created thread and the originating thread. In other words, the originating thread has to wait until the new thread signals it that it has created the object.
I'm trying to get my head around what you are trying to do. It looks overly complicated for something like a thread-class. Would you mind post the class-definition as well?
Start by removing the C-style cast of the process-argument to CreateThread():
this->hThread = ::CreateThread (NULL, 0,&runProcess, (void *)(this_param), 0, &this->hThreadId);
If this doesn't compile you're doing something wrong! Never ever cast a function pointer! If the compiler complains you need to change your function, not try to cast away the errors! Really! You'll only make it worse for yourself! If you do it again they* will come to your home and do ... Let's see how you like that! Seriously, don't do it again.
Btw, in Process() I think it would be more appropriate to do something like:
assert(::GetCurrentThreadId() == hThreadId);
But if you declare it private it should only be accessible by your CThread-class anyway and therefor it shouldn't be a problem. Asserts are good though!
*It's not clear who they are but it's clear whatever they do it won't be pleasant!
As Rob Walker pointed out - I really missed the race condition. Also the crash is not when getting the pointer, but when using it.
A simple wait did the job:
MyClass* myPointer = thread.getMyPointer();
while (myPointer == 0)
{
::Sleep(1000);
}
myPointer->someMethod(); // Working :)