tags:

views:

118

answers:

4

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 :)

+9  A: 

Depends 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.

Carl Norum
Why "char *s" wouldn't work at runtime? Because of the operating system?
Dor
However using `const char * s = "a literal string";` will work, as this is the declaration of a pointer to constant data. The string literal is constant data, so this works.
Thomas Matthews
@Thomas, that code fragment won't even compile if you put const in there; gcc gives me "error: assignment of read-only location", as expected in that case.
Carl Norum
@Dor, yes, the operating system probably controls the read/write status of any particular memory location. The first code fragment above causes a bus error on my Mac; on embedded devices I've worked on, it would have been totally successful.
Carl Norum
+2  A: 

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.

Jon Benedicto
+1  A: 

Literal strings are always const. You can point to them, but not write over them. You have two options there:

  1. 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.

  2. Copy the string to writable memory:

    char *s = malloc(30);
    strncpy(s, "Hello you beautiful people", 30);
    
Chuck
A: 

Attempting to modify a string literal invokes undefined behavior. It's best to treat string literals as unwritable.

John Bode