Sushant Kr
Sushant Kr

Reputation: 1973

how is memory allocated when a character pointer points to a string?

#include<stdio.h>

int main(void)
{
    /* in this amessage is an array big enough to
     * hold  the sequence of character and '\0' */
    char amessage[] = "now is the time";

    /* in this case a character pointer is
     * pointing to a string constant */
    char *pmessage = "now is the time";

    return 0;
}

I am confused how is the memory allocated in the second case?? Is that copy of memory private....I mean is it safe to write something as 2nd stmt and be sure that anything else will not overwrite the same memory??

Upvotes: 2

Views: 450

Answers (3)

pmg
pmg

Reputation: 108978

The string literals can be distinct or not: it's the compiler choice (the C99 Standard says it is unspecified).

Suppose, for a minute, that changing the string literals themselves wasn't UB.

int main(void) {
    char *p = "now is the time";
    /* compiler makes sure there is a place with "now is the time"
    ** and makes p point there */
    char *q = "time";
    /* possibly, the compiler reuses the time from
    ** the previous string literal */

    q[0] = 'd'; /* technically UB: don't do this */
    puts(p);    /* possibly writes "now is the dime" */
}

As tou your specific question: as long as you don't invoke UB, it's safe. The memory allocated by the compiler takes into account all other uses of all other objects.

Upvotes: 2

Alok Save
Alok Save

Reputation: 206518

char *pmessage = "now is the time";

Creates a string literal, the memory for the string is allocated somewhere in a read only location, it is implementation dependent detail of compilers to be specific.

Modifying it will lead to an Undefined Behavior. So If you are using string literal it is your responsibility to ensure that you do not try to write to this read only memory.

Upvotes: 6

lang2
lang2

Reputation: 11966

It's safe. They'll be allocated on the stack. The only thing different between amessage and pmessage is that pmessage is read only.

Upvotes: -4

Related Questions