1

I have simply program to write. I try to make it with pointers. It is program which is changing uppercase to lowercase without index from function argument. Problem is with changing value, my program is crashing there...

#include <iostream>
#include <cstring>

using namespace std;

char* male(char* nap, int n) {
    for (int i = 0; i < 9; ++i) {
        if (i != n && ((*nap >= 'A') && (*nap <= 'Z'))) {
            *nap = (char)(*nap+32);
        }
        nap++;
    }
    return nap;
}

int main() {

    char * nap = "aBCDEFGHI";
    male(nap, 2);

    return 0;
}

Could you tell me why *nap = (char)(*nap+32); is not a good way?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
K.Dot
  • 29
  • 4

2 Answers2

2

This is C++ code so following:

char * nap = "aBCDEFGHI";

should be

const char * nap = "aBCDEFGHI";

because string literals are const in C++. So your code :

*nap = (char)(*nap+32);

is also Undefined Behaviour, which can result in crash.


minimal change to remove UB is to define nap as array:

char nap[] = "aBCDEFGHI";
marcinj
  • 48,511
  • 9
  • 79
  • 100
2

Your compiler is supposed to complain of this line...

char * nap = "aBCDEFGHI";

Your major problem is that you are trying to modify a string literal at run-time. Its Undefined Behavior to do so. See Why is this string reversal C code causing a segmentation fault?

This answer explains your workaround.

Could you tell me why *nap = (char)(*nap+32); is not a good way?

Its not all that bad per se. But you can get into trouble with it... That line is effectively...

*nap = *reinterpret_cast<char*>(const_cast<char*>(nap+32));

C-style cast is a ruthless cast. as you can see, you are also casting away all const and/or volatile qualifications... There are some code bases that will hurt, especially if the object was stored in a read only marked memory... See When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68