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

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

问题描述

我们能否在 C 中检查传递给函数的指针是否分配了内存?

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

我用 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 .. ??

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

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

我知道我的函数会被一个优秀的 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天全站免登陆