1

In my C application, I have a logging method similar to this:

void logError(const char* module, const char* message, ... );

When this method is called, callers often do something like the following:

logError("foo", "bar");

// or even

#define FOOMODULE "foo"
logError(FOOMODULE, "bar");

No matter how the char* module gets passed in, the char* is static memory stored in the application binary.

My question is, does the compiler/linker collapse all instances of a statically declared string into a single declaration? As such, is it valid to assume that comparing the pointers ("foo" == FOOMODULE) of my statically declared strings will always work as expected (assuming, of course, that the strings are equivalent as in my example above and that both are indeed statically allocated in the app's binary)?

I'm working on a way to filter on log messages as they come in. For example, perhaps I only want to see log messages from a single 'module'. It would be great to compare the pointers and not each byte in the string when deciding if I want to actually print a given log message.

Thanks!

Brett
  • 4,066
  • 8
  • 36
  • 50

2 Answers2

3

It will often work, but it is not guaranteed and such a comparison should not be used.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • So when in objective c, Apple compares the pointers to strings (which are method names), is that memory dynamically allocated? This deserves its own question... – Brett Dec 12 '12 at 03:43
  • Perhaps a link of some kind to back this up? – Brett Dec 12 '12 at 03:44
2

I'm going to give a deliberately different answer.

If you are going to do this, write solid test cases, because whether or not this works depends on both the compiler and the optimizations enabled. The standard allows but does not require deduping of string constants.

Joshua
  • 40,822
  • 8
  • 72
  • 132
  • What's the point in testing something that you know is unpredictable? Testing makes sense to ensure you've properly used something that's supposed to be predictable. But there's no point in finding out how something we know is unpredictable happens to behave under some combinations of conditions since we already know we can't rely on it. – David Schwartz Dec 12 '12 at 05:25
  • So you know the constraints were violated by the failing test. – Joshua Dec 12 '12 at 17:21