本文介绍了堆栈内存上的 free()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Solaris 上支持一些 c 代码,而且我看到了一些奇怪的东西,至少我认为是这样的:

I'm supporting some c code on Solaris, and I've seen something weird at least I think it is:

char new_login[64];
...
strcpy(new_login, (char *)login);
...
free(new_login);

我的理解是,由于变量是一个本地数组,内存来自堆栈,不需要被释放,而且由于没有使用 malloc/calloc/realloc,所以行为是未定义的.

My understanding is that since the variable is a local array the memory comes from the stack and does not need to be freed, and moreover since no malloc/calloc/realloc was used the behaviour is undefined.

这是一个实时系统,所以我认为这是在浪费周期.我错过了一些明显的东西吗?

This is a real-time system so I think it is a waste of cycles. Am I missing something obvious?

推荐答案

你只能 free() 你从 malloc(),calloc() 或 realloc() 函数中得到的东西.释放堆栈上的某些东西会产生未定义的行为,幸运的是这不会导致程序崩溃或更糟.

You can only free() something you got from malloc(),calloc() or realloc() function. freeing something on the stack yields undefined behaviour, you're lucky this doesn't cause your program to crash, or worse.

认为这是一个严重的错误,并尽快删除该行.

Consider that a serious bug, and delete that line asap.

这篇关于堆栈内存上的 free()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:49