Search code examples
cmingwclion

Error writing to a pointer that solves by changing pointer to array. What's happening?


So I was programming a sudoku solver in C, and I came up with something I didn't expect.

The sudoku was stored as a global pointer to a char.

char *sudoku=
        "200050713"
        "431000805"
        "675800094"
        "016075000"
        "740268901"
        "052914037"
        "527600109"
        "164090382"
        "080102006";

At some point of the program naturally I had to write to the array, to keep it simple (and legal) let's say:

sudoku[1] = '1';

I am receiving a SIGSEGV at that line. This solves by just changing the type of the global variable sudoku to an array.

char sudoku[] = ...

There aren't any other variables or functions named sudoku if you are wondering. I'm curious about this behavior, is a global pointer read-only?


Solution

  • I'm curious about this behaviour, is a global pointer read-only?

    It has nothing to do with globals. Invokding char *s = "asdf" creates an array in read only memory and the points the pointer s to it. Well, to be more accurate it's not necessarily read only memory, but it could be, and irregardless it's undefined behavior trying to write to it. It's about the same as doing this:

    const char arr[] = "asdf";
    char *s = arr;
    

    Your second attempt, however, initializes an array, and notice how similar it is to the first line in the above snippet. Just remove const and you have the same.