1

I've been trying to better understand C strings and I got through this question (Is it possible to modify a string of char in C?) explaining the difference between the following two declarations of a string.

char *a = "This is a string";
char b[] = "This is a string";

Now, if I have function to process a string such as:

int process_string(char *x);

Is there a way to determine whether x could be modified inside the function? Can I determine whether x points to read-only or modifiable memory space at runtime?

jmbo
  • 13
  • 3

1 Answers1

1

No, the standard C language has no way to do this. You are expected to resolve this issue by program design instead of by runtime checks. For instance, have two different functions and make every caller call the right one.

Yes, it is somewhat inconvenient and has the potential for mistakes. That's C for you.

There might be ways to perform such a detection using system-specific information and interfaces, e.g. comparing the address of the string to segment start and end addresses. At best they would work only on that platform, and generally will still be very sensitive to choice of compiler, compiler version, OS version, system configuration, compilation flags, etc, etc. Debugging would be the only sensible reason to do it (if the function expects a writable string and someone is passing one that isn't writable); even so, most systems will have more convenient ways to detect such a bug (e.g. write it and see if you get a segfault).

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82