c - 在 C 中的非堆对象上使用 free()

标签 c

我找不到此操作的实际行为。
它似乎不会导致任何运行时错误,所以我猜它什么都不做?

最近我在写类(class)作业时才发现这种技术。
实际上,我的教授似乎是这个的倡导者,但我无法在不破坏的情况下理解它是如何工作的。
基本上,这个想法是使用一个变量作为一个测试对象或一个结构指针的守卫,然后将这个“虚拟”变量传递给一个函数。
我会尝试用代码给出一个例子:

#include <stdio.h>
#include <stdlib.h>

struct Struct {
    int a;
    struct Struct *next;
    float c;
};

int
stuff(struct Struct *ptr) {
    free(ptr);
    return 1; // always assume true for the sake of example
}

int
main(int argc, char *argv[]) {
    struct Struct *ptr;
    struct Struct test;
    int retval;

    if ((ptr = malloc(sizeof(struct Struct *))) == NULL) {
        fprintf(stderr, "ERROR: could not allocate memory\n");
        return -1;
    }

    // some magic goes here...
    test = *ptr;
    retval = stuff(&test);
    if (retval) {
        free(ptr);
    }

    return 0;
}

在我的类(class)作业中,我必须依次释放一个结构的两个结构指针成员,然后释放该结构的内存。由于任何一个结构指针成员都可以对数据进行操作,如果不能释放一个成员,则不应释放整个主结构,并且应恢复更改。
这种通过堆栈上的变量来确定是否可以在不影响运行数据的情况下安全释放内存的方法让我感到困惑。我不确定我什至不明白什么。
谁知道这种方法论的细节?

最佳答案

couldn't find what the behaviour of [using free() on non-heap objects in C] action actually is.

这是未定义的行为。就是这样,您不能对将要发生的事情做出任何假设。 test*ptr 内存的副本。在 malloc(和 friend )未返回的指针上调用 free 会导致未定义的行为。

要么你误解了你的教授,要么你的教授不知道他/她在说什么。您需要做的就是阅读文档:

The behavior is undefined if ptr does not match a pointer returned earlier by malloc(), calloc() or realloc(). Also, the behavior is undefined if the memory area referred to by ptr has already been deallocated, that is, free() or realloc() has already been called with ptr as the argument and no calls to malloc(), calloc() or realloc() resulted in a pointer equal to ptr afterwards.


It doesn't seem to cause any run-time errors so I guess it just does nothing?

欢迎来到 C :)。你已经习惯了当你做错事时立即打你的手的语言。 C并不真正关心你做什么。 C 给了你自由,但这种自由是双向的(也就是说,你也可以自由地离开)。

关于c - 在 C 中的非堆对象上使用 free(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21566670/

相关文章:

c++ - 将值从数组转换为ascii?

c - sizeof argv[1] 不工作

C结构体中的代码片段 uint8_t : 5 what does that mean?

c - C中的面向对象

c - malloc() 函数的返回

检查字符串是否改变

c - 如何使用 `stat`通过符号链接(symbolic link)获取最终终点的路径

c - 文件服务器及其关联的客户端

c - 在动态数组实现中使用 realloc()

c - 如何在 execlp 系统调用后打印行