0

My bad!!I had assumed that the following excerpt from a notorious yet wildly popular book is totally valid C.But only today I was pointed out that it's ridden with UB (though I am yet to find how come it's so).Hence here's that particular section from the book.You will be doing me and many other "victims" like me a great favor if you can point out in a numbered manner what is wrong or UB with each particular statement,and the appropriate corrections for those.

char *p = "Hello" ;  /* pointer is variable, so is string */ 
*p = 'M' ;  /* works */ 
p = "Bye" ;  /* works */ 


const char *q = "Hello" ;  /* string is fixed pointer is not */ 
*q = 'M' ;  /* error */ 
q = "Bye" ;  /* works */ 


char const *s = "Hello" ;  /* string is fixed pointer is not */ 
*s = 'M' ;  /* error */ 
s = "Bye" ;  /* works */ 


char * const t = "Hello" ;  /* pointer is fixed string is not */ 
*t = 'M' ;  /* works */    
t = "Bye" ;  /* error */ 


const char * const u = "Hello" ;  /* string is fixed so is pointer */ 
*u = 'M' ;  /* error */ 
u = "Bye" ;  /* error */ 
4

2 に答える 2

1

これら 2 つのケースは未定義の動作です。

char *p = "Hello" ;
*p = 'M' ;  // Undefined behavior: trying to modify a string literal.


char * const t = "Hello" ;
*t = 'M' ;  // Undefined behavior: trying to modify a string literal.
于 2013-04-28T18:33:15.537 に答える
1
char *p = "Hello"

"Hello" is a string literal placed in implementation read only memory and modifying it in any possible way is an UB. Irrespective of where you put the const qualifier any attempt to modify the string literal is a UB. The correct way to represent this in C++ is:

const char *p = "Hello";

char *p = "Hello" ;

Pointer can be reseated but the string should not be modified.

const char *q = "Hello" ;
char const *s = "Hello" ;

The correct way to represent a pointer pointing to string literal in C++. The pointer can be reseated but the string should not be modified.

char * const t = "Hello" ;

Pointer cannot be reseated and the string should not be modified.

const char * const u = "Hello" ;

Pointer is constant so is the string.

Any attempt to modify the string in any of these is an UB.

于 2013-04-28T18:28:13.700 に答える