宏定义导致数据异常问题

复制代码
/*
 * Copyright (C) gtc.
 */


#ifndef _GTC_QUEUE_H_INCLUDED_
#define _GTC_QUEUE_H_INCLUDED_

#include "gtc_core.h"


typedef struct gtc_queue_s  gtc_queue_t;

struct gtc_queue_s {
    gtc_queue_t  *prev;
    gtc_queue_t  *next;
};


#define gtc_queue_init(q)                                                     \
    (q)->prev = q;                                                            \
    (q)->next = q


#define gtc_queue_empty(h)                                                    \
    (h == (h)->prev)


#define gtc_queue_push(h, x)                                                  \
    (x)->next = (h)->next;                                                    \
    (x)->next->prev = x;                                                      \
    (x)->prev = h;                                                            \
    (h)->next = x


#define gtc_queue_tail(h)                                                     \
    (h)->prev


#define gtc_queue_remove(x)                                                   \
    (x)->next->prev = (x)->prev;                                              \
    (x)->prev->next = (x)->next


#define gtc_queue_pop(h)                                                      \
    gtc_queue_remove(h->prev)                                              


#define gtc_queue_data(q, type, link)                                         \
    (type *) ((u_char *) q - offsetof(type, link))


#endif /* _GTC_QUEUE_H_INCLUDED_ */
复制代码

上述是一个队列的实现,这个队列实现是有问题的,问题在于 gtc_queue_pop 这个宏定义。
宏定义本质上是一种替换,gtc_queue_pop 中调用了 gtc_queue_remove ,这里的传参有讲究,
gtc_queue_remove 的入参是 h->prev,当执行 gtc_queue_remove 中 (x)->next->prev = (x)->prev; 语句时
会导致 h->prev 的指向发生了变化,导致下面的执行出现异常,宏不同于函数,它的简单替换可能会带来一些奇怪的问题
特此做好记录。

posted on   寒魔影  阅读(26)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
历史上的今天:
2016-01-15 c语言 数组名是常量指针

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示