EXC_BAD_ACCESS error while s[1] = 0; C, Xcode

Viewed 25

After I create a string s, I used s[2] = '\0'; to short string s to length of 2. However, it shows me Thread 1: EXC_BAD_ACCESS error. I had changed 2 to other integers but it still gives me the same error.

1 Answers

There may be an issue with your compiler, but the problem as describe works for non-constant strings.

#include <stdio.h>

int main() {
    char s[] = "My String";

    s[2] = '\0';
    printf("|%s|\n", s);
}

Tested on both clang 13.1.6 and gcc 12:

% cc -o EXC EXC.c ; ./EXC
|My|

Clang and gcc both report issues when the declaration is a constant. const char s[] = "My String";

EXC.c:6:10: error: cannot assign to variable 's' with const-qualified type 'const char [10]'
    s[2] = '\0';
    ~~~~ ^
EXC.c:4:16: note: variable 's' declared const here
    const char s[] = "My String";
    ~~~~~~~~~~~^~~~~~~~~~~~~~~~~
1 error generated.

EXC.c: In function 'main':
EXC.c:6:10: error: assignment of read-only location 's[2]'
    6 |     s[2] = '\0';
      |          ^

Another issue is writing past the end of the string. s[10] = '\0';

EXC.c:6:5: warning: array index 10 is past the end of the array (which contains 10 elements) [-Warray-bounds]
    s[10] = '\0';
    ^ ~~
EXC.c:4:5: note: array 's' declared here
    char s[] = "My String";
    ^
1 warning generated.
Related