开发者

QThread and reading memory

I have faced such a problem. I have a library which allows through UDP inter-process communication. It is very straight forward. The library creates shared memory available for other processes to write and read from. When process wants to read a interested memory it passes a string value which uniquely points to corresponding shared memory and passes pointer to container (char array) where he expects to receive result of reading. Library supplies safe multi-threading.

I have a exception when thread has left a run() routine.

Exception: is access violation and it is raised in

void __cdecl _freeptd (
        _ptiddata ptd
        )
{
        /*
         * Do nothing unless per-thread data has been allocated for this module!
         */

        if ( __flsindex != 0xFFFFFFFF ) {

            /*
             * if parameter "ptd" is NULL, get the per-thread data pointer
             * Must NOT call _getptd because it will allocate one if none exists!
             * If FLS_GETVALUE is NULL then ptd could not have been set
             */

            if ( ptd == NULL
#ifndef _M_AMD64
                 && (FLS_GETVALUE != NULL)
#endif  /* _M_AMD64 */
                )
                ptd = FLS_GETVALUE(__flsindex);

            /*
             * Zero out the one pointer to the per-thread data block
             */

            FLS_SETVALUE(__flsindex, (LPVOID)0);

            _freefls(ptd);
        }

        if ( __getvalueindex != 0xFFFFFFFF ) {
            /*
             * Zero out the FlsGetValue pointer
             */
            TlsSetValue(__getvalueindex, (LPVOID)0);
        }
} 

code:

char* memory = new char(2000);
string struct_name = "struct";
bool m_running = false;
void Reader::run()
{
    initalizeLibrary();
    m_running = true;
    //loop
    while(true)
    {
              if ( ! m_running ) break;
              library->readFromSharedMemory(struct_name, memory);
    }

    finalize();
}

void Reader::stop()
{
     m_running = false;
}
开发者_如何学编程

Exception is raised only when we allow to library->readFromSharedMemory(struct_name, memory);. _freeptd cannot access memory which cause access violation.

I need a hand. Thx in advance.


I think the problem is the line

char* memory = new char(2000);

this code means you want to allocate only one char size of memory, and the memory is initialized by 2000.

If you are intent to allocate 2000 characters size of memory, you should use this

char* memory = new char[2000];

And delete it later by using

delete [] memory;

I hope this will help you to fix the access violation issue.


I have found a solution:

if you allocate memory: char* memory = new char(2000); it will fail, if you will use char* memory = (char*) malloc(2000); and then free up accordingly, it will work. I suppose it has something with new and different way of allocation a memory by compiler.

Lukasz.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜