有没有一种方法(纯C语言)可以区分使用
当然,我可以倒着搜索代码并确保变量是否是使用
malloc
分配的字符串和字符串字面量而不知道哪个是哪个?严格来说,我想找到一种检查变量是否为使用malloc
分配的字符串的方法,如果是,我将释放它;如果不是,则让它保持不变。当然,我可以倒着搜索代码并确保变量是否是使用
malloc
分配的,但是万一有简单的方法存在……编辑:添加了几行以使问题更具体。char *s1 = "1234567890"; // string literal
char *s2 = strdup("1234567890"); // malloced string
char *s3;
...
if (someVar > someVal) {
s3 = s1;
} else {
s3 = s2;
}
// ...
// after many, many lines of code an algorithmic branches...
// now I lost track of s3: is it assigned to s1 or s2?
// if it was assigned to s2, it needs to be freed;
// if not, freeing a string literal will pop an error
s2
,那么如果s3
将被赋值为s1
或s2
,而且没有其他的操作,你是否关心s3
?你不会两次释放由strdup
返回的字符串,因此如果你无论如何都要释放s2
,那么你为什么还要关心s3
呢? - Lasse V. Karlsens2
和s3
上都调用free
,你最终会得到未定义的行为。 - Ed S.char *s1 = "1234567890"
是合法的代码,但最好写成const char *s1 = "1234567890"
。请参见 https://dev59.com/z3A75IYBdhLWcg3wboYz。 - chux - Reinstate Monica