我想知道是否可以检查传递给函数的指针是否由malloc/calloc/realloc分配?
int main(){
struct something o;
struct something *a;
a = malloc(sizeof(struct something));
freeSome(&o);/*This would normally throw an (corruption?) error*/
freeSome(a);/*This is fine*/
}
void freeSome(struct something * t){
if (/*expression here*/){
free(t);
}
}
Run Code Online (Sandbox Code Playgroud)
我明白,通常你会检查是否t == NULL,但我只是想知道是否有可能看到是否已为给定指针分配内存.
在我正在研究的程序中,我有一个类似的结构
typedef struct _mystruct{
char* my_string;
} mystruct;
Run Code Online (Sandbox Code Playgroud)
大多数时候my_string是使用malloc分配的,所以有一个函数可以调用
free(mystructa->my_string);
Run Code Online (Sandbox Code Playgroud)
通常这是有效的,但在某些时候,my_string被设置为文字
my_string = "This is a literal";
Run Code Online (Sandbox Code Playgroud)
在我调用free()之前有没有办法告诉两者之间的区别?