The memory address of constants in C

Viewed 299

I'm learning about pointers in C and I've got a few questions. Here's a piece of code just for an example.

int var = 300;
char s[] = "Clang";
char *p  = "Wonder";

I know that all the variables have their addresses in memory. The variables like var and s and p have their own addresses in memory.

But I wonder if constants have memory addresses as well.

Do 300,"Clang", "Wonder" themselves have memory addresses?

3 Answers

Memory usage of variables and constants is a matter of compiler implementation. In practice, constants defined like this:

const *foo = "bar";
const int answer = 42;

will usually occupy memory and have addresses. That is, some place in the program's address space at run-time you'll find the sequence of bytes representing the text "bar" and the sequence of bytes representing the number 42.

However, because of the aggressive optimization done by modern compilers, it's plausible that some constants may have no run-time existence at all. For example, in a snippet like this:

const int foo = 3;
int x = foo * 4;

it's conceivable that, if foo is never used anywhere else, the compiler might (in effect) convert this to:

int x = 12;

and foo won't even exist at runtime.

Incidentally, many developers think of C pre-processor macros as "constants":

#define PI 3.14159

These usually don't occupy memory at run-time, because they are substituted into the code at compilation time.

Only objects and functions have addresses in C. Named variables are objects. A string literal "Wonder" used by itself is an object, an array of 7 characters (i.e. char[7]) - the 6 visible characters and the terminating null character - and therefore may have an address. The literal "Clang" is a borderline case here, strictly speaking it does not have an address because it is not an object but just a special initializer syntax.

The C model is quite unlike Python programming language, where

a = 300

a is a name that has no address, whereas 300 is an object that has an address.

The may is because while C says that an object or function has an address, many compilers optimize code, creating an executable that does not follow the strict C abstract machine; therefore an object might have an address only if you observe it.

Most implementations place objects in "sections" usually called .text (code), .data - initialized data, .bss - zeroed data, .rodata - read only data.

Related