Free()在动态库功能中不起作用? [英] Free() not working in dynamic library function?

查看:71
本文介绍了Free()在动态库功能中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是我的代码,用于创建动态链接库函数,以便为main函数中的指针值分配内存,并将其传递给动态库函数,然后在库中释放指针..

主要功能:

Hi,

This is my coding for creating dynamic link library function to allocate memory for a pointer value in main function and pass it to dynamic library function and free the pointer there in library..

MAIN FUNCTION:

int main(int argc, char* argv[])
{
    int *p=NULL;
    p=new int(100);
    printf("\nMemory allocated for pointer 1 and size is %d\n",p);
    fn1(p);
    return 0;
}


库功能:

DYNLIB_API void fn1(int *p)
{
	printf("\nThis is lib func 1\n");
	free(p);
	printf("\npointer 1 memory cleared and size is %d\n",p);
}


该代码已成功编译.但是在运行时,在执行库函数中的free()行时出现了中止程序的错误.

如何清除?

请帮助我...


The code successfully compiled. But during run-time I got an error to abort the program while it executes the free() line in library function.

How to clear it?

Please help me...

推荐答案

糟糕!

当您使用 new 获取一些内存时,必须使用 delete 释放它.

如果要使用 free ,则必须使用 malloc 获取内存.

因此,就您而言...您以错误的方式混合了内存处理技术.

希望这会有所帮助.

哦:请看一下这个链接 [ ^ ].
Ouch!

When you use new to get some memory you MUST use delete to free it.

If you want to use free, you must get the memory using malloc.

So in your case... you are doing it in the wrong way mixing memory handling techniques.

Hope this helps.

Oh: and please, take a look at this link[^].


不要这样做(在不同的模块中分配和取消分配),请参见
Don''t do that (allocate and deallocate in different modules) see Allocating and freeing memory across module boundaries[^].


还有其他东西,尽管这不是您的问题,我想也很有趣;这句话:
Something else, although this wasn''t your question, I think is interesting to mention as well; this statement:
printf("\nMemory allocated for pointer 1 and size is %d\n",p);



...将打印p的存储位置.从文字上判断,这不是您想要的吗?元素的数量可以这样打印:



...will print the memory location of p. Judging from the text, that is not what you want? The number of elements could be printed like so:

printf("\nNumber of elements in p: %d\n",*p);



分配的内存大于元素数,因为100个整数均大于1个字节,并且存储了其他信息(例如元素数).



The memory allocated is more than the number of elements, since the 100 integers are larger than 1 byte each and there is additional information (such as number of elements) stored.


这篇关于Free()在动态库功能中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆