[英]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.