Michał
Michał

Reputation: 711

Does data under address assigned using #define can be overwritten?

I have a hard time uderestanding how #define works when combined with pointers.

Here is my pseudocode:

#define ID "28"      // I need to keep it as string

int main()
{
    char * my_id = ID;
    ...
    ...
}

Now what is actually my_id pointing to ? I did not call alloc nor statically allocated memory for my variable so can data under address my_id be overwritten?

Upvotes: 0

Views: 56

Answers (3)

Chris Rouffer
Chris Rouffer

Reputation: 763

The string "28" will be stored in a section of your executable. The pointer, my_id, will point to the address of the string "28".

Edited to remove mistaken reference to 'stack'. Thank you commenters for your clarification.

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134376

After preprocessing, your snippet looks like

 char * my_id = "28";

so, my_id points to the string literal "28".

For string literals, it basically is a null terminated character array with static storage duration. But, attempt to modify a(ny) string literal causes undefined behavior.

Quoting C11, chapter §6.4.5, String literals, paragraph 6,

In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals.78) The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence. [...]

and paragraph 7,

[...] If the program attempts to modify such an array, the behavior is undefined.

So, TL:DR, my_id points to the string literal, or for the sake of accuracy, it holds the address of the first element of the null-terminated array with static storage, initialized with the content "28".

Upvotes: 1

dbush
dbush

Reputation: 224822

A #define just does text substitution. So what you have is equivalent to:

char *my_id = "28";

What this means is that my_id points to the string constant "28". String constants are typically stored in a read-only data section, so there's nothing to allocate/deallocate.

Upvotes: 1

Related Questions