如何在堆或文字字符串区分? [英] How to distinguish between strings in heap or literals?

查看:125
本文介绍了如何在堆或文字字符串区分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例在那里我可以在内存或文字分配的字符串指针。现在,后者不能被释放,所以这是一个问题,如果我传递了错误的。有没有办法知道哪一个是分配的,哪些不是?

I have a use case where I can get pointers of strings allocated either in memory or literals. Now the latter can't be freed so that's a problem if I pass the wrong one. Is there a way to know which one is allocated and which not?

char *b = "dont free me!";
if(!IS_LITERAL(b)) {
    free(b);
}

我想类似的东西。

I imagine something like that.

我的例子:

方案1:文字

char *b = "dont free me!";
scruct elem* my_element = mylib_create_element(b);
// do smth
int result = mylib_destroy_element(my_element); // free literal, very bad

情景2:堆

char *b = malloc(sizeof(char)*17); // example
strncpy(b, "you can free me!",17);

scruct elem* my_element = mylib_create_element(b);
// do smth
int result = mylib_destroy_element(my_element); // free heap, nice

如何在用户通话 mylib_create_element(B); 不是我的控制之下。如果他之前 mylib_destroy_element 释放它可能会崩溃。因此,它一定是 mylib_destroy_element 的清理。

How the user calls mylib_create_element(b); is not under my control. If he frees before mylib_destroy_element it can crash. So it has got to be mylib_destroy_element that cleans up.

推荐答案

我最近也有类似的情况。下面是我所做的:

I've had a similar case recently. Here's what I did:

如果你正在做接受字符串指针,然后用它来创建一个对象( mylib_create_element ),一个好的想法是的的API副本字符串的一个单独的堆缓冲区,然后释放它由您决定。这样一来,的用户负责的用于释放他在调用您的API,这是有道理的使用的字符串。这是他的字符串,毕竟。

If you're making an API that accepts a string pointer and then uses it to create an object (mylib_create_element), a good idea would be to copy the string to a separate heap buffer and then free it at your discretion. This way, the user is responsible for freeing the string he used in the call to your API, which makes sense. It's his string, after all.

请注意,如果你的API取决于用户创建对象后更改字符串这是不行的!

Note that this won't work if your API depends on the user changing the string after creating the object!

这篇关于如何在堆或文字字符串区分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆