[英]Why does freeing a pointer cause program to abort?
我一直在处理个人项目的函数指针和结构。 当我编译并运行我的代码时,我尝试释放指针时出现“中止(核心转储)”错误。
我有以下代码(不包括导入):
typedef int (*intFunction)(int,int);
typedef struct {
int value;
intFunction func;
} ValueFunc;
int addInts(int a, int b){
return a + b;
}
int main(){
ValueFunc vf;
vf.value = 3;
vf.func = &addInts;
int y = vf.func(vf.value,4);
printf("%i",y);
free(vf.func);
return 0;
}
如果有人能解释为什么会这样,我会非常感激。
您只需要free
动态分配的内容(例如,使用calloc
, malloc
或该系列中的任何函数)。
你从未分配内存,所以你不需要释放它。 并且将随机指针传递给free
函数将使其行为异常。
发现这个: http : //bytes.com/topic/c/answers/504956-do-you-have-delete-function-pointer用户说:
你不应该删除函数指针。 该函数位于可执行文件中的某个位置。 执行程序时,操作系统会将可执行文件加载到内存中。 当程序为函数指针赋值时,它将获得指向可执行文件中函数位置的值。 如果你在程序中删除它,你的编译器很可能会抱怨你试图删除一个不是指针的对象。
...所以即使你的编译器没有给出任何错误,它也很可能在执行期间失败
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.