Sam Porch Sam Porch - 1 year ago 71
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;


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

return 1;

example use:

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

strcpy(newString, "Example one");

SafeFree("Example two");

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download