PDA

View Full Version : something awfully newbie




wala
Jul 24, 2006, 04:08 PM
What am I doing wrong here?

#include <stdio.h>

char *change_string(char *);

int main()
{
printf("%s\n", change_string("a string"));
return 0;
}


char *change_string(char *string)
{
string[0] = ' ';
return string;
}



almightyshoe
Jul 24, 2006, 05:33 PM
What's the problem? It compiled in gcc just fine.

EDIT: I think I see it. There might be a problem with your return; the pointer should point...somewhere else.

wala
Jul 24, 2006, 07:04 PM
I think I see the problem. When I comment out the line "string[0] = ' '", the program works. So then, what if the memory inside the scope of a function is not allowed to be written to outside of that function... the "protected memory" feature I read about in OS X.

To test my theory, I tried compiling for an OS without protected memory. Not finding a compiler for Classic, I installed TurboC 2.01 (http://community.borland.com/article/0,1410,20841,00.html) under dosbox, and compiled my program there. To my surprise it ran correctly.

So my current theory is that quite simply, Darwin is trying to protect me from myself.
That would also explain why I've never read about this kind of thing, and would explain the nature of the error message I get under OS X.

But wait, hold on. If you replace "string" with an integer array and modify everything else in the program appropriately, the integer array is allowed to be changed. Perhaps the memory protection only happens with strings. Either way this is getting complicated....

AussieSusan
Jul 24, 2006, 11:03 PM
Depending on your compiler, string literals are sometimes placed in read-only memory. Therefore when you try to "modify" the first character, you may get an illegal memory operation.

What is the "problem" you get reported?

wala
Jul 25, 2006, 12:48 AM
"Bus error" under all versions of gcc I have (including Apple and fink). But this problem isn't restricted to string literals.
I found a thread at http://www.thescripts.com/forum/thread215466.html which explains something like this. Evidently a char * is read-only, but a char[] isn't (I tried it out that way, it works).