Sam Porch Sam Porch - 4 days ago 5
C Question

In C, will a literal string address always be greater than any allocated string address?

I'm attempting to differentiate literal strings from allocated strings so I don't accidentally try to free() literal strings, which would cause a segfault.

The reason I might try to free() literal strings involve a strcat() wrapper that can be embedded thusly:

strcatex("My name ", strcatex("is ", strMyName));


Regardless of the reason, consider:

void* mallocex(int intBytes)
{
void* newPtr;

newPtr = malloc(intBytes);

if(newPtr == 0)
return 0;
else if(newPtr > maxPointer)
maxPointer = newPtr;

return newPtr;
}


and

int SafeFree(void **ptr)
{
if((unsigned long) ptr > (unsigned long) maxPointer)
return 0;
else
free(*ptr);

return 1;
}


example use:

char *newString;
newString = (char*) mallocex(12);

strcpy(newString, "Example one");

SafeFree(&newString);
SafeFree("Example two");


Will this always work, regardless of how large my heap becomes?

Answer

There is no such guarantee don't rely on it.
A string literal is allocated memory somewhere in the read-only implementation defined region there is no way to know what that will be in a portable manner and hence you should not make any assumptions about it.

Comments