Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

wala

macrumors member
Original poster
Jun 3, 2005
46
0
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

macrumors regular
Jun 4, 2006
118
0
B-Town, India
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

macrumors member
Original poster
Jun 3, 2005
46
0
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 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

macrumors member
May 29, 2006
54
0
Melbourne, Australia
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

macrumors member
Original poster
Jun 3, 2005
46
0
"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).
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.