简体   繁体   English

Free不会释放作为va_arg列表发送的指针

[英]Free doesn't free pointers sent as a va_arg list

I want to free a variable list of pointer with the freeS macro below: freeS(s1,s2,...); 我想用下面的freeS宏释放指针的变量列表:freeS(s1,s2,...);

My code doesn't free the first pointer despite getting a print with the first pointer address from the freeSF function. 尽管从freeSF函数获得带有第一个指针地址的打印结果,但是我的代码并未释放第一个指针。 In main, free(s1) works but it should. 总的来说,free(s1)有效,但应该可以。 free(s2) in main crashes as expected. 在主要崩溃中免费(s2)。

How can I free the s1 pointer in the freeSF function? 如何在freeSF函数中释放s1指针?

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

#define freeS(...) freeSF("", __VA_ARGS__, NULL)
void freeSF(char *paramType, ...) {
    va_list pl;

    va_start(pl, paramType);
    paramType = va_arg(pl, char *);
    while (paramType) {
        printf("arg %p\n", paramType);
        free(paramType);
        paramType = va_arg(pl, char *);
    }
    va_end(pl);
}

int main(int ARGC, char** ARGV) {
    char *s1 = strdup("1");
    char *s2 = strdup("2");
    printf("s1 %p, s2 %p\n", s1, s2);
    freeS(s1, s2);
    free(s1);
}

Your program exhibits undefined behavior because you are double freeing. 您的程序表现出未定义的行为,因为您要进行两次释放。

With undefined behavior, anything can happen. 使用未定义的行为,可能会发生任何事情。 Your program may crash, it may output strange results, or (in this case) it may appear to work properly. 您的程序可能崩溃,可能会输出奇怪的结果,或者(在这种情况下)它似乎可以正常运行。 Adding a seemingly unrelated change, such as a call to printf or adding an unused local variable, can change the way undefined behavior manifests itself. 添加看似无关的更改(例如,调用printf或添加未使用的局部变量)可能会更改未定义行为的显示方式。

In this case, calling free(s1) in main isn't causing a crash. 在这种情况下,在main调用free(s1)不会导致崩溃。 It's still undefined behavior. 仍然是未定义的行为。 For example, when I run this code it doesn't crash. 例如,当我运行此代码时,它不会崩溃。 But if I add a call to malloc just before calling free(s1) , it does crash. 但是,如果我在调用free(s1)之前添加了对malloc调用,则会崩溃。

Just because the code can crash doesn't mean it will . 仅仅因为代码崩溃并不意味着崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM