2

I have written my implementation of strupr function from string library. When I call this function, the program crashes. I have already found an another way to make it working but I am wondering why this verion isn't working. Program crashes exactly during executing the *str = (*str) - 32; instruction.

#include <iostream>

using namespace std;

char * my_strupr(char * str)
{
    char * result = str;

    while(*str != '\0')
    {
        if(*str >= 'a' && *str <= 'z') *str = (*str) - 32;
        str ++;
    }

    return result;
}

int main()
{
    char * str = "some text";
    cout << my_strupr(str);
    return 0;
}

I have to use pointers in this case, they are required in my task.

Kamil Turek
  • 77
  • 1
  • 6

1 Answers1

1

The compiler is storing the string in read-only memory, and you are getting a seg-fault trying to modify this memory. This is discussed here

PiedPiper
  • 5,735
  • 1
  • 30
  • 40