验证从malloc返回的指针 [英] validate pointer that was returned from malloc

查看:70
本文介绍了验证从malloc返回的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




有没有一种标准方法来验证指针是否指向由malloc分配的内存是什么?

TIA

Hi,

Is there a standard way to validate if a pointer points to memory that was
allocated by malloc?
TIA

推荐答案

Bryan Bullard写道:
Bryan Bullard wrote:
有没有一种标准方法来验证指针是否指向内存是由malloc分配的吗?
Is there a standard way to validate if a pointer points to memory that was
allocated by malloc?




No.


-

Best问候,

Andrey Tarasevich



No.

--
Best regards,
Andrey Tarasevich


>有没有一种标准方法来验证指针是否指向由malloc分配的
> Is there a standard way to validate if a pointer points to memory that was
的内存?




你必须自己编写那个malloc的包装器 -

可能很有趣。 :)


Kristofer



You would have to write your own wrapper for malloc for that one - that
might be fun. :)

Kristofer


Bryan Bullard写道:
Bryan Bullard wrote:
是否有标准方式




验证指针是否指向malloc分配的内存?
cat onStack.c
Is there a standard way
No.
to validate if a pointer points to memory that was allocated by malloc? cat onStack.c



#include< stdio.h>

#include< stdlib.h>


int onStack(void * p){

return(p>(void *)& p);

}


int main(int argc,char * argv []){

char c;

char * p =& c;

// char * p =(char *)malloc(sizeof(char));

if(onStack(p)){

fprintf(stdout ,

p可能指向自动存储中的角色。\ nn;);

}

else {

fprintf(stdout,

p可能指向静态数据或免费存储。\ n;);

}

返回0;

}


#include <stdio.h>
#include <stdlib.h>

int onStack(void* p) {
return (p > (void*)&p);
}

int main(int argc, char* argv[]) {
char c;
char* p = &c;
//char* p = (char*)malloc(sizeof(char));
if (onStack(p)) {
fprintf(stdout,
"p probably points to a character in automatic storage.\n");
}
else {
fprintf(stdout,
"p probably points to static data or free storage.\n");
}
return 0;
}


这篇关于验证从malloc返回的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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