你能确定一个字符串用C freeable? [英] Can you determine if a string if freeable in C?

查看:77
本文介绍了你能确定一个字符串用C freeable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我说:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char *x;
char *y;

int main() {
        x = malloc(sizeof("Hello, world!"));
        strcpy(x, "Hello world!");
        y = "Hello, world";
        free(x);
        fprintf(stderr, "okay");
        free(y);
}

然后,很明显,该程序将打印好之后,死去,因为被释放的指针没有被分配的-obviously因为该字符串是一个字符串。

Then, obviously, the program will print "okay" followed by dying because the "pointer being freed was not allocated"—obviously, because the string was a string literal.

我想写给出字符串时什么都不做的功能,但由于非字符串时,通话免费。这是可能的,如果是这样,怎么样?

I'd like to write a function that does nothing when given string literals, but calls free when given non-string literals. Is that possible, and if so, how?

推荐答案

没有。在C中,你必须保持跟踪你分配自己是什么。

No. In C, you have to keep track of what you've allocated yourself.

一些的malloc 实现(如的 dlmalloc )用于检查堆提供一些额外的功能,但你不应该依赖这些。 dlmalloc 所具有的功能 dlmalloc_inspect_all ,它会走堆,并返回到你所有的内存区域的的malloc 已分配的,除了内存映射块。所以,你可以使用,如果一个指针指向一个非存储器映射分配进行测试,但它仍然是一般一个坏主意。

Some malloc implementations (such as dlmalloc) provide some extra functionality for inspecting the heap, but you shouldn't rely on those. dlmalloc has the function dlmalloc_inspect_all, which will walk the heap and return to you all of the regions of memory that malloc has allocated, except for memory-mapped chunks. So you could use that to test if a pointer points to a non-memory-mapped allocation, but it's still a bad idea in general.

和Windows上,甚至不考虑使用[ IsBadReadPtr ]测试是否指针指向可读存储器或不 - 的它应该被称为 CrashProgramRandomly

And on Windows, don't even think about using [IsBadReadPtr] to test if a pointer points to readable memory or not -- it should really be called CrashProgramRandomly.

这篇关于你能确定一个字符串用C freeable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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