检查是否指针被分配内存或不 [英] Checking if a pointer is allocated memory or not

查看:162
本文介绍了检查是否指针被分配内存或不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们能不能​​检查传递给函数的指针是否与内存或不是在C分配?

Can we check whether a pointer passed to a function is allocated with memory or not in C?

我已经wriiten用C我自己的函数,它接受一个字符指针 - BUF [指向缓冲区]和尺寸 - buf_siz [缓冲区的大小。调用这个函数用户之前实际上已经创造了缓冲并为它分配buf_siz内存。

I have wriiten my own function in C which accepts a character pointer - buf [pointer to a buffer] and size - buf_siz [buffer size]. Actually before calling this function user has to create a buffer and allocate it memory of buf_siz.

既然有机会,用户可能会忘记做内存分配和简单地传递指针,我的功能我想检查。那么,有没有办法,我可以在我的功能检查,看看是否通过指针真正的内存量buf_siz分配??

Since there is a chance that user might forget to do memory allocation and simply pass the pointer to my function I want to check this. So is there any way I can check in my function to see if the pointer passed is really allocated with buf_siz amount of memory .. ??

EDIT1:似乎有检查它没有标准库..但没有任何肮脏的黑客来检查它.. ??

It seems there is no standard library to check it .. but is there any dirty hack to check it .. ??

EDIT2:我知道我的功能将受到良好的C程序员使用...但是我想知道我们是否可以检查或不..如果我们能我会喜欢听它..

I do know that my function will be used by a good C programmer ... But I want to know whether can we check or not .. if we can I would like to hear to it ..

结论:所以这是不可能的检查,如果一个特定的指针在函数内部分配的内存或不

推荐答案

您不能检查,除了一些具体的实施黑客。

You cannot check, except some implementation specific hacks.

指针与他们没有其他信息比它们指向哪里。你能做的最好是说:我知道这个特定的编译器版本如何分配内存,所以我会取消引用的内存,将指针移动回4个字节,检查大小,确保它匹配......等等。你不能这样做在一个标准的方式,因为内存分配是实现定义。更何况,他们可能还没有动态地分配它。

Pointers have no information with them other than where they point. The best you can do is say "I know how this particular compiler version allocates memory, so I'll dereference memory, move the pointer back 4 bytes, check the size, makes sure it matches..." and so on. You cannot do it in a standard fashion, since memory allocation is implementation defined. Not to mention they might have not dynamically allocated it at all.

您只需要承担你的客户知道如何在C程序的唯一未解决方案,我能想到的将是你自己分配内存,并返回它,但这几乎没有一个小的变化。 (这是一个更大的设计更改。)

You just have to assume your client knows how to program in C. The only un-solution I can think of would be to allocate the memory yourself and return it, but that's hardly a small change. (It's a larger design change.)

这篇关于检查是否指针被分配内存或不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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