gpt4 book ai didi

c - 什么时候释放字符串指针?

转载 作者:可可西里 更新时间:2023-11-01 11:48:53 27 4
gpt4 key购买 nike

我有一个定义如下的宏。同样在我的程序中,我需要以两种样式打印出错误消息:

  1. PRINT_ERR("这是错误!");
  2. 使用 asprint 构建日志字符串并打印出来:
 char *log = NULL;
int age = 0;
asprintf(&log, "error: %s on: %d", "Name", age);
PRINT_ERR(log);

使用下面的宏定义,样式#1 将抛出异常。那么,在宏定义中,我如何确定在什么情况下,我需要释放字符串“y”?

#define PRINT_LOG(x, y) { \
printf ( "%s: %s\n", x, y);\
free(y);\ //how do I know "y" is a pointer, or a string like this "string"?
}

#define PRINT_ERR(y) { PRINT_LOG ("ERR ", y) }

最佳答案

您不能使用两个不同的宏 - 如下所示吗?

#define PRINT_ERR(y) ....

#define PRINT_ERR_FREE(y) \
do { \
PRINT_ERR(y); \
free(y);\
} while (0);

关于c - 什么时候释放字符串指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32404907/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com