类型字符串和strdup [英] Typecasting string and strdup

查看:138
本文介绍了类型字符串和strdup的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个输入const字符串以某种方式被修改(这导致C编译器警告),什么是最好的方式来处理它 - 类型转换为一个新的变量,然后使用它或复制它,并使用它,然后释放它。或者有任何其他方法来处理这种类型的场景。请建议。任何帮助将不胜感激。

If an input const string is being modified in some way (which is resulting in C compiler warning), what is the best way to handle it - typecasting it to a new variable and then using it OR duplicating it and using it and then freeing it. Or is there any other way to handle this type of scenario. please suggest. Any help would be appreciated.

//类型

const char * s1;
char * s2 = (char *)s1;

//重复且免费

const char * s1;
char * s2  = strdup( s1 );
free(s2)

编辑:不是C ++。我不知道在typecasting,s2会是一个新的字符串s1的副本,还是会指向原来的字符串s1?

It is a C compiler; not C++. I am not sure whether in typecasting, s2 will be a new copy of string s1 or will it be pointing to the original string s1?

感谢您的答案。我还有一个怀疑 -

Thanks for the answers. I have one more doubt-

const char * c1;
const char * c2 = c1;

上述作业是否有效?

推荐答案

在这里强制转换const可能会关闭编译器,但会导致运行时失败。制作一个字符串的副本,并对其进行处理。

Casting away const here might shut the compiler up but will lead to runtime failures. Make a copy of the string and work on that.

强制转换const不会复制内存的内容。它只是创建一个指向同一内存的指针,并告诉编译器它可以直接前进并写入该内存。如果内存为只读,则您有保护故障。更严重的是,你可以有正确性问题,很难调试。不要丢弃const。

Casting away const does not copy the contents of the memory. It just creates a pointer to the same memory and tells the compiler that it can go right ahead and write to that memory. If the memory is read only you have a protection fault. More seriously you can have correctness problems which are hard to debug. Don't cast away const.

当然,如果你需要修改一个变量,并让这些修改对调用者可见,那么你不应该使它在const第一名。另一方面,如果修改意味着函数是私有的,那么const参数的复制是最好的。

Of course, if you need to modify a variable and have those modifications visible to the caller, then you should not make it const in the first place. On the other hand, if the modifications are meant to be private to the function, then duplication of the const parameter is best.

作为一个广义的规则,你应该避免如果可能的话。 Cast是最常见的错误来源之一。

As a broad rule you should attempt to avoid casts if at all possible. Casts are one of the most frequent sources of errors.

这篇关于类型字符串和strdup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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