Typecasting string and strdup

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 12:01:20

问题


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.

//Typecasting

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

//Duplicate and free

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

EDIT: 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;

Is the above assignment valid?


回答1:


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.

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.

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.

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




回答2:


If the array that s1 points to is const then you must not modify it; doing so gives undefined behaviour. In that case, if you need to modify it, then you will have to take a copy. UPDATE: Typecasting will give you a pointer to the same array, which is still const, so you still must not modify (even though trying to do so no longer gives a compile error).

If you can guarantee that the array is not const, then you could modify it by casting away the const from the pointer. In that case, it would be less error-prone if you can enforce that guarantee by not adding a const qualifier to s1 in the first place.




回答3:


If your input is a const char* you definitely should listen to the compiler warning and leave it alone.



来源:https://stackoverflow.com/questions/7722140/typecasting-string-and-strdup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!