Results 1 to 3 of 3
If I do something similar to this :
Code:
char *g_text = "abcde";
void main(void)
{
g_text[2] = 'x';
}
I get a segmentation fault. I'm guessing its not allowed ...
- 09-05-2008 #1Just Joined!
- Join Date
- Sep 2008
- Posts
- 1
Is this allowed ?
If I do something similar to this :
I get a segmentation fault. I'm guessing its not allowed to change memory assigned like this, but is there a way to do this ? maybe a compiler setting or something ?Code:char *g_text = "abcde"; void main(void) { g_text[2] = 'x'; }
I know I could write this totally different and use malloc etc, but I'm porting existing code from sco unix to redhat linux and there are a lot of variables like these, so making it work would mean a lot of extra work.
- 09-05-2008 #2
Hello,
the ANSI C standard says that these so called "string literals" are to be assumed unmodifiable and any try to modify them at runtime will result in undefined behaviour. 3.1 Lexical Elements
Therefore, it's better to write.
If you want to be able to modify it later, you could reserve a constant sized array and have it initialized automatically with such a string.Code:const char *g_text = "abcde";
The size of the array will be set by compiler automatically so that the string and the trailing 0 fits in. But the size will stay constant.Code:char g_text[] = "abcde";
Debian GNU/Linux -- You know you want it.
- 09-05-2008 #3
if your create a variable like:
char *g_text = "abcde";
it will produce a variable in the section called rodata(read only data) which is read only.
while char g_text[] = "abcde"; does not
try compiling your program with gcc -S programname.c and look at the programname.s file, in the first example you'll see the rodata section in the second you won't
so is this allowed...g_text[2] = 'x'....no its not...hope this helps...Gerard4143


Reply With Quote