相关疑难解决方法(0)

在C中自动释放堆栈变量

不幸的是,在C中没有任何智能指针..但是有可能构建一个宏来包装变量声明并在离开声明变量的范围时使用该变量作为输入变量调用函数调用吗?

很抱歉这个长短语,但我正在使用xnu内核,你有许多内置引用计数器的元素,并且一定不要忘记在使用它时不用这个元素来避免内存泄漏.

例如,如果我有以下类型proc_t:

struct proc;
typedef struct proc * proc_t;
Run Code Online (Sandbox Code Playgroud)

我想在范围内基于此类型声明堆栈变量,例如:

{
    proc_t_release_upon_exit proc_t proc_iter = proc_find(mypid);
    //the rest of the code in this scope 
}
Run Code Online (Sandbox Code Playgroud)

在预处理器分析宏之后和编译之前,我希望生成以下代码:

{ 
    proc_t myproc = proc_find(mypid)
    //the rest of the code in scope
    proc_rele(myproc);
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在C中定义这样的宏?

c variables macros

32
推荐指数
2
解决办法
2523
查看次数

是否指向void的指针总是安全的?

#include <stdio.h>

void swap(void *v[], int i, int j)
{
    void *tmp;

    tmp = v[i];
    v[i] = v[j];
    v[j] = tmp;
}

int main(void)
{
    char *s[] = {"one", "two"};
    printf("%s, %s\n", s[0], s[1]);
    swap(s, 0, 1);
    printf("%s, %s\n", s[0], s[1]);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

one, two

two, one
Run Code Online (Sandbox Code Playgroud)

警告: no compatible pointer casting, need void**, but char

我使用这个程序来模拟K&R中的交换函数,以演示函数指针的使用,我的问题是它的转换是否void pointer总是安全的,或者是否有任何替换它的方法.

c pointers void

3
推荐指数
1
解决办法
458
查看次数

如何在 C 中实现 Go 的 defer() 以便允许声明变量?

在这个现代 C视频中,有一个技巧可以推迟代码的执行,直到块/作用域退出。它的使用方法如下:

\n
int main()\n{\n    int foo=0, bar;\n    const char *etc = "Some code before defer";\n\n    defer(profile_begin(), profile_end())\n    {\n        /* Some code, which will be automatically \n         * preceded by call to profile_begin() and\n         * followed by run of profile_end().*/\n         foo++;\n         bar = 1;\n    }\n\n    etc = "Some code after defer";\n    foo = bar + 1;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

视频中的实现:

\n
#define macro_var_line(name) concat(name, __LINE__)\n#define defer(start,end) for( \\\n        int macro_var_line(done) = (start,0); \\\n        !macro_var_line(done); \\\n        (macro_var_line(done) += 1), end)\n
Run Code Online (Sandbox Code Playgroud)\n …

c gcc c-preprocessor c11 gcc-extensions

3
推荐指数
1
解决办法
2382
查看次数

标签 统计

c ×3

c-preprocessor ×1

c11 ×1

gcc ×1

gcc-extensions ×1

macros ×1

pointers ×1

variables ×1

void ×1