开发者

Freeing main program memory from within a dll crushes in Visual studio 2010

I encountered a strange issue while coding a .dll file in C with gcc compiler and then tried to use it through MSVC and visual studio. The .dll compiles correctly and is correctly used by test programs compiled and linked with gcc. But when I try to do use the .dll 开发者_JAVA百科in Visual studio I get a strange runtime crush. I have identified the issue and would appreciate your input as to why is this happening.

In the test program we have a function which allocates a buffer, populates it in some way (depending on the user) and then returns the buffer. The user has to implement it on his own. Something like below:

float* decode(void* data, int dataSize, int par1, int par2,int par3)
{ 

    //allocate the memory for the data
    float* d =  (float*)malloc(sizeof(float)*dataSize);

    //do something to populate the data here

    //return data
     return d;
}

The dll has two functions which actually take a function pointer to that use-rmade function and use it to get that float* buffer. Then the .dll uses this function to create and use the data and after the usage it frees them.

Something like below:

void DLL_Func(void* data,unsigned int inputPN,float* (*decode)(void*,int,int,int,int))
{

    //use the user-made decode function
    float* nData = (*decode)(data,inputPN,par1,par2,par3);

    //do stuff here

    //before returning free the data buffer since it is no longer needed
    free(nData) //<--- Crushes the program only in Visual Studio
 }

Well I isolated the problem in that free(). Works fine if I use my dll from a gcc compiled program but MSVC compiled program crushes at that point and gives this:

 Unhandled exception at 0x7714e1fe in vstudiotest.exe: 0xC0000005: Access violation reading location 0x1e6dca5e.

Which I guess means that for the MSVC compiler what my dll does is forbidden. Is this just some MSVC quirk or should GCC also crush but does not and will come back in the future and torture me with this problem?

Of course the solution is to change it somehow so that the buffer is also freed by the user and not the .dll but I would like to understand the reason this is happening first.


memory must be allocated and freed with the same CRT. This means in general that you should try to free memory in the same module it was allocated in to avoid these types of issues. If this isn't possible you must link to the same version of the CRT.

MSVC will complain if you try to link to different versions of the MS CRT, but I'm guessing that you are linking to some other version that MSVC doesn't know about.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜