I'm making a bit of C code compile as C++ and have come across something that's puzzling me. Consider the following function taken from LuaFileSystem.
static const char *perm2string (unsigned short mode) {
static char perms[10] = "---------";
//static char* perms = "---------";
int i;
for (i=0;i<9;i++) perms[i]='-';
if (mode & _S_IREAD)
{ perms[0] = 'r'; perms[3] = 'r'; perms[6] = 'r'; }
if (mode & _S_IWRITE)
{ perms[1] = 'w'; perms[4] = 'w'; perms[7] = 'w'; }
if (mode & _S_IEXEC)
{ perms[2] = 'x'; perms[5] = 'x'; perms[8] = 'x'; }
return perms;
}
This code will work correctly, however if I uncomment the commented line, it crashes. I've stepped over this with a debugger and it seems that with static char* perms
the string is placed in read-only memory and so the first loop will cause an access violation, using the static array causes no such issues. I'm curious as to why this is happening when the string isn't declared const.