1

I'm practicing on Code Wars and I've encountered a strange problem. Omitting some details: the task is to replace each digit by its complement to 9, and shift each letter by a given number. To do so I've made this loop, which I believe should change each character based on its ANSI code representation:

char *str = "ABC 123!"; // example
int n = 1; // example

for (char *c = str; *c; c++) {
    printf("Before: *c = %d\n", *c);
    if (*c > 47 && *c < 58) {
        *c = 105 - *c;
        // replace digit
    }
    if (*c > 64 && *c < 91) {
        *c = (*c - 64 + number) % 26 + 64;
        // replace letter
    }
    printf("After: *c = %d\n", *c);
}

I've made various log statements in various places from which I can tell that some condition checking fails and I don't enter the if block, while the other succeeds and I do enter the if block, but as soon as I run into the *c = ...; statement, the test crashes (also tried running the same code in a separate IDE, but the execution still suddenly stops).

Why would this happen?

Alex F
  • 394
  • 1
  • 12

1 Answers1

1

Attempting to modify the string literal has undefined behavior. In your case the program stopped because you tried to modify the non-modifiable. (Generally it is placed in .rodata section - read only).However, modifying a mutable array of char directly, or through a pointer is not undefined behavior, even though its initializer is a literal string. The following is fine:

char str[] = "ABC 123!";

This is all you need to get the correct behavior out of your code. Also one of the reasons we don't write code in binary is make things human readable. Here instead of using 47,58 use '0' or '9' etc. It's more readable.

user2736738
  • 30,591
  • 5
  • 42
  • 56