"Strange" access violation writing error c++

Started by
5 comments, last by rip-off 15 years, 3 months ago
Hi, it seems that I have a problem with a c++ rtrim (removes spaces from a string on the right side) function I borrowed from dosbox source code. The function implementation is the following: char *rtrim(char *str) { char *p; p = strchr(str, '\0'); while(--p>=str && isspace(*reinterpret_cast<unsigned char *>(p))); p[1] = '\0'; return str; } Compiling is fine, when debugging I get : Unhandled exception at 0x0041756c in test.exe: 0xC0000005: Access violation writing location 0x0041d803 on the p[1]='\0' assignment, even if the assignment in the immediate window works just fine. I use visual studio 2008. Any ideas would be appreciated, thanks in advance.
Advertisement
char *rtrim(char *str){    for (char *p = strchr(str, '\0') - 1 ; p >= str && isspace(*p) ; --p)        *p = '\0';        return str;}


(untested)

Anyway, I think p[1] is the problem.
Also, what do you pass to rtrim? You can't do something like:
char* trimmed = rtrim("test string       ");
Quote:Original post by janta
Anyway, I think p[1] is the problem.


Thanks for the quick answer, indeed p[1]='\0' is the problem.

Quote:
Also, what do you pass to rtrim? You can't do something like:
char* trimmed = rtrim("test string       ");



That's exactly what I pass, why would it be a problem? Just a reminder, everything works fine in immediate window, p[1] assignment is ok and str pointer indeed holds the trimmed string after the assignment, that's why I am confused with this.
Modifying a character literal is undefined/implementation defined behavior.
In fact it should't compile because
"test string       "

is const.

However doing
char str[] = "test string       ";rtrim(str);

is ok.
Did you mean C? Because in C++ we prefer to avoid playing with raw character arrays.
std::string rtrim(const std::string &str){	std::string::size_type index = str.find_last_not_of(' ');	return str.substr(0,index == std::string::npos ? index : index + 1);}
However, a space is not the only type of white space the OP might want to avoid. ('\r', '\n', '\t'...)

And the op's function modifies the string in-place even when not assigning the result back to the original value.

I'm not implying that an idiomatic C++ equivalent version can't be written.
It is a fairly easy thing to add to that code, what with std::string::find_last_not_of having an overload that accepts a string of characters to match. Doing that is left as an exercise to the OP [smile]

This topic is closed to new replies.

Advertisement