Is it OK that a char* variable will point to a string (that's written in the source code)?
Can I manipulate/modify the space allocated for the literal string as long as I'm not exceeding it's length?
As much as I understand the format of an executable, it's fine, but I want to be sure. Thank you :)
views:
118answers:
4Depends a bit on your runtime characteristics, but in general, doing something like:
char *s = "a literal string";
s[3] = 'q';
will compile, but not work at runtime. The literal string in this case is generally in a read-only section of the executable. The following example, however, will work:
char s[] = "a literal string";
s[3] = 'q';
In this case, the literal string is an initialiser for an array (s
) on the stack. So the answer to your first question is "yes" and the answer to your second question is "maybe".
There is a semantic difference between the two examples. The first one creates a pointer to a literal string, and the second creates an array and initialises it with the contents of a literal string.
Is it OK that a char* variable will point to a string (that's written in the source code)?
It is generally OK, but I'd mark the pointer as const to prevent unintentional modifications.
Example: const char *Str = "This is a hard string.";
Can I manipulate/modify the space allocated for the literal string as long as I'm not exceeding it's length?
I would not recommend this. If you need to modify the string, copy it to a memory chunk that you've allocated.
Literal strings are always const. You can point to them, but not write over them. You have two options there:
An actual array:
char s[] = "Hello you beautiful people";
This works because you aren't pointing to the literal string; you're initializing the array (which is writable) to the contents of the literal string.
Copy the string to writable memory:
char *s = malloc(30); strncpy(s, "Hello you beautiful people", 30);
Attempting to modify a string literal invokes undefined behavior. It's best to treat string literals as unwritable.