c - 如何区分动态分配的 char* 和静态 char*

标签 c arrays string pointers free

在我正在处理的程序中,我有一个类似的结构

typedef struct _mystruct{
    char* my_string;
} mystruct;

大部分时候my_string是使用malloc分配的,所以有一个函数调用

free(mystructa->my_string);  

通常这是有效的,但在某些时候,my_string 被设置为文字

my_string = "This is a literal"; 

有没有办法在调用 free() 之前区分两者?

最佳答案

没有办法可靠地区分指向文字的指针和指向已分配内存的指针。您将不得不推出自己的解决方案。有两种方法可以解决这个问题:

1) 在 struct 中设置一个标志,指示是否应释放指针。

typedef struct _mystruct {
    char *my_string;
    int string_was_allocated;
} mystruct;

mystructa.my_string = malloc(count);
mystructa.string_was_allocated = 1;
.
.
if (mystructa.string_was_allocated)
   free(mystructa.my_string);

mystructa.my_string = "This is a literal";
mystructa.string_was_allocated = 0;

2) 始终使用 strdup 进行动态分配。

mystructa.my_string = strdup("This is a literal");
free(mystructa.my_string);

这两种方法都涉及对现有代码的更改,但我认为解决方案 2 更加健壮、可靠和可维护。

关于c - 如何区分动态分配的 char* 和静态 char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28866966/

相关文章:

c - 如何在我的代码中实现二维指针数组来满足要求?

c - 在C中读取字符串

javascript - 在 JavaScript 中,我可以检查是否可以在不实际评估字符串的情况下评估它吗?

c - 为什么在我的 UDP 服务器上尝试使用 sendto() 时会收到错误的地址错误?

python - 使用索引分割 Numpy 数组

c - Learn C the Hard Way 的 ex17 数据库设计问题

arrays - 如何在 Haxe 中检查参数的类型

javascript - 使用 JavaScript 突出显示网页上的每个单词,一次一个

android - 我们可以访问我的安卓手机的麦克风驱动程序吗

c - 英特尔内部函数 : multiply interleaved 8bit values