简体   繁体   English

检查变量是静态分配还是动态分配?

[英]Check if a variable was statically or dynamically allocated or not?

I'm implementing my own malloc and free functions. 我正在实现自己的malloc和free函数。 How can I have an error check that passes in a static variable over a dynamically allocated variable? 如何进行将动态变量传递给静态变量的错误检查? Let's say I have: 假设我有:

char foo[10];
void *bar = malloc(5); 

void free(void *p)

Is there a way to tell the user that this is an error? 有没有办法告诉用户这是一个错误?

free(foo)

Your best bet is to maintain a table of allocated pointers within your memory management functions. 最好的选择是在内存管理功能中维护分配的指针表。

Don't forget to remove entries when releasing memory. 释放内存时不要忘记删除条目。

This might sounds crazy , 这听起来很疯狂,

You need to maintain your allocated pointers from your custom malloc() function in a list/structure. 您需要在列表/结构中维护自定义malloc()函数分配的指针。 Then when using your custom free() function check whether variable exists inside your maintained list/structure. 然后,在使用自定义的free()函数时,请检查所维护的列表/结构内部是否存在变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 是否更快地访问静态或动态分配的内存? - Is accessing statically or dynamically allocated memory faster? 使用getpwnam()时静态分配的变量 - statically allocated variable when using getpwnam() C何时发布静态分配的变量声明 - When will C release statically allocated variable declarations 如何创建静态分配的动态大小的数组? - How can I create a statically allocated dynamically sized array? 如果在动态/静态分配的双精度数组中输入字符,会发生什么情况? - What happens if I enter a character to a dynamically/statically allocated double array? 静态分配的指向静态分配结构的指针数组 - Statically allocated array of pointers to statically allocated structures C 中动态分配的结构指针和静态分配的结构指针之间有区别吗? - Is there a difference between dynamically allocated pointer to structure and statically allocated pointer to structure in C? 堆栈中的变量是“静态分配的”吗? - Are variables on the stack “statically allocated”? “静态分配”是什么意思? - What is the meaning of “statically allocated”? C语言:为什么动态分配的对象返回指针,静态分配的对象为您提供选择? - C Language: Why do dynamically-allocated objects return a pointer, while statically-allocated objects give you a choice?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM