Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c char pointer problem

Tags:

c

if we declare char * p="hello"; then since it is written in data section we cannot modify the contents to which p points but we can modify the pointer itself. but i found this example in C Traps and Pitfalls Andrew Koenig AT&T Bell Laboratories Murray Hill, New Jersey 07974

the example is

char *p, *q;
p = "xyz";
q = p;
q[1] = ’Y’;

q would point to memory containing the string xYz. So would p, because p and q point to the same memory.

how is it true if the first statement i mentioned is also true.. similarly i ran the following code

main()
{
char *p="hai friends",*p1;
p1=p;
while(*p!='\0') ++*p++;
printf("%s %s",p,p1);
}

and got the output as ibj!gsjfoet

please explain how in both these cases we are able to modify contents? thanks in advance

like image 683
ashna Avatar asked Dec 07 '22 02:12

ashna


2 Answers

Your same example causes a segmentation fault on my system.

You're running into undefined behavior here. .data (note that the string literal might be in .text too) is not necessarily immutable - there is no guarantee that the machine will write protect that memory (via page tables), depending on the operating system and compiler.

like image 154
Yann Ramin Avatar answered Dec 21 '22 05:12

Yann Ramin


Only your OS can guarantee that stuff in the data section is read-only, and even that involves setting segment limits and access flags and using far pointers and such, so it's not always done.

C itself has no such limitation; in a flat memory model (which almost all 32-bit OSes use these days), any bytes in your address space are potentially writable, even stuff in your code section. If you had a pointer to main(), and some knowledge of machine language, and an OS that had stuff set up just right (or rather, failed to prevent it), you could potentially rewrite it to just return 0. Note that this is all black magic of a sort, and is rarely done intentionally, but it's part of what makes C such a powerful language for systems programming.

like image 44
cHao Avatar answered Dec 21 '22 04:12

cHao