Thursday, November 20, 2008

Segment fault in strcpy

Just today I was doing some programming work on a Sun machine helping to port some code from an older Sun machine to the newer OS.

The client suspected that it was a compiler problem because the newly compiled versions of the same source code didn't work - and they no longer had access to the old compiler.

Using dbx, I discovered that the crash was occuring in the strcpy function, which is pretty well sure to be bug free.

What transpired was that the program was trying to copy into a string, which the newer compiler was optimising into a read-only segment of the library.

The here's the old and new definitions of the variable:


char* string = "initial string value"; /* read only segment, causes crash in strcpy */
char string[100] = "initial string value"; /* read only segment, causes crash in strcpy */
char string[100]; /* uninitialised places the variable in read-write segment - strcpy into this variable works */


This took a few hours to discover, so hopefully sharing this information will save someone else a short piece of their life. :)

No comments: