Is macro more secure than static const if I don't want someone to know or change the hardcode value?

142 views Asked by At

I searched some topic about

#define PASSWORD "abcde"

and

static const char* PASSWORD="abcde";

It seems that #define does not store the value in memory (I am not sure if it is right). I heard it may have some tools can detect and access which memory address is using during app execution (e.g.:change some value for a game). I afraid, if I use static const char* PASSWORD, someone may know the value of PASSWORD by detecting the address of PASSWORD and get the value of PASSWORD by getting the content in the address.

Is it better to use #define if I want the hardcode value more safe?

2

There are 2 answers

6
cehnehdeh On

Doesn't matter in this case. Since both use a string-literal, the string itself will be stored in the string pool, as opposed to existing somewhere dynamically on the heap. Also, macros technically don't even exist, since the compiler simply replaced all instances of the macro with the #define definition. During runtime, the program won't see a difference.

EDIT: As someone mentioned, if you want to mess with security, look into hashing. This would make it much more difficult to pull out the password with a memory-searching program.

0
Guillaume Racicot On

You may want to use you variable as constant expression.

constexp char* = "abc";

It is better than a define and the variable exists only at compile time, so the variable don't have any address at all. However, just like a define, it will print "abc" into the binary directly. You may want to mix this with hashing.