When you write

const char *ptr = "blah blah";

then the following happens: the compiler generates a constant string (of type char []) with the contents "blah blah" and stores it somewhere in the data segment of the executable (it basically has a similar storage duration to that of variables declared using the static keyword).

Then, the address of this string, which is valid throughout the lifetime of the program, is stored in the ptr pointer, which is then returned. All is fine.

Does this mean that "blah blah" is not a local variable inside getString()?

Let me respond with a broken English sentence: yes, it isn't.

However, when you declare an array, as in

const char a[] = "blah blah";

then the compiler doesn't generate a static string. (Indeed, this is a somewhat special case when initializing strings.) It then generates code that will allocate a big enough piece of stack memory for the a array (it's not a pointer!) and will fill it with the bytes of the string. Here a is actually a local variable and returning its address results in undefined behavior.

So...

But I thought that const char *ptr and const char a[] were basically the same thing.

No, not at all, because arrays are not pointers.

Answer from user529758 on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › c language › storage-for-strings-in-c
Storage for Strings in C - GeeksforGeeks
July 23, 2025 - ->A ->a ->k ->a ->s ->h As you can see so many allocations involved that made heap costly. To make it efficient, memory for large string is allocated on heap whereas for small string it is allocated on static buffer.
Top answer
1 of 5
12

When you write

const char *ptr = "blah blah";

then the following happens: the compiler generates a constant string (of type char []) with the contents "blah blah" and stores it somewhere in the data segment of the executable (it basically has a similar storage duration to that of variables declared using the static keyword).

Then, the address of this string, which is valid throughout the lifetime of the program, is stored in the ptr pointer, which is then returned. All is fine.

Does this mean that "blah blah" is not a local variable inside getString()?

Let me respond with a broken English sentence: yes, it isn't.

However, when you declare an array, as in

const char a[] = "blah blah";

then the compiler doesn't generate a static string. (Indeed, this is a somewhat special case when initializing strings.) It then generates code that will allocate a big enough piece of stack memory for the a array (it's not a pointer!) and will fill it with the bytes of the string. Here a is actually a local variable and returning its address results in undefined behavior.

So...

But I thought that const char *ptr and const char a[] were basically the same thing.

No, not at all, because arrays are not pointers.

2 of 5
6

I guess that if it were a local variable, I would not be able to pass it to my main() function... But if it's not, where is it stored?

String literals are usually stored in a read-only data section (.rodata). C standard just say they have static storage duration. Therefore you can return a pointer to such literal, but it is not the case of arrays.

In the following example, the object pointed by p1 has static storage duration, whereas the array p2 has automatic storage duration.

char *f(void)
{
    const char *p1 = "hello, world";
    char p2[] = "hello, world";

    return p1; /* allowed */
    return p2, /* forbidden */
}
🌐
Substack
andrewjohnson4.substack.com › p › understanding-how-c-strings-are-stored
Understanding How C Strings Are Stored in the Data Section of a C Program
October 24, 2024 - When we declare a string in a C program, it can be either statically allocated or dynamically allocated. Statically allocated strings (like string literals) are stored in the Data segment, which is ...
🌐
Quora
quora.com › How-are-strings-represented-in-memory-in-C
How are strings represented in memory in C? - Quora
Answer (1 of 6): Historically the answer is that strings were stored as a contiguous block of data type char. Each char is 1 byte and is a binary representation mapped onto ASCII character set with one extra byte at the end of the string set to NULL.
🌐
Reddit
reddit.com › r/cprogramming › i've a question about memory when using strings
r/cprogramming on Reddit: I've a question about memory when using strings
November 2, 2023 -

Edited to add another question about pointing to local variables with global pointers. This has been solved. The solution I found is at the end.

From what I understand, I can do the following:

char *myString = "";
myString = "Hello World";
myString = "Goodbye";

And this would not be wrong. However, thinking a bit into it, it makes no sense to me, because when/how is memory being allocated/rellocated/freed for this? First of all I make a string with 0 chars, so it needs 0 bytes. Then it needs ~11 bytes, then only 7. The memory needed to store the string is changing, but at no point in time have I done anything with memory, so is C managing it in the background? Does C not manage it and therefore this is wrong? What would happen if I now did myString=NULL;? Would that leave allocated memory with no one pointing to it?

To hijack my own post and not spam, an additional question about memory. If I create a variable inside a function, say int myLocalInt;, C automatically reserves memory for that variable to be stored in, so I don't need to do any malloc shit. If I then declare a pointerint *myLocalIntPtr;, I can make that pointer point to that variable's memory (myLocalIntPtr=&myLocalInt) and I wouldn't need to do malloc, right?And now for the important question. In the previous example with the local int, what would happen if I assigned a global pointer the memory address of the local int when the function the int is local to ends?

int *globalPtr;
int someFunction(){
    int myLocalInt = 5;
    globalPtr = &myLocalInt;
    printf("Of course this would print 5: %d",*globalPtr);
    return 0;
}
int main(){
    someFunction();
    printf("But what about now? Is it still 5? i=%d",*globalPtr);
}

I just realized I can test that myself, so I'll go do that. Beside that, I understand that C releases all local variables when their block ends, but given that there's still a pointer to it I thought it might not.

If it was freed, globalPtr would now be aiming at non-allocated memory, which is a problem. Especially because I don't know how to check if a block of memory is currently allocated. (I guess I could try calling free on it, and if there's an error it's not allocated). I understand this would give undefined behaviour, with it being possible that the print outside still gives 5, or it might give some other number if the memory has been altered, or could give an error.

Testing did not help much, however thinking did. It seems memory allocated to local variables will always be freed when the local variable goes out of scope. However, if the variable is a pointer, and it was allocated memory with malloc or any of those, that memory is still reserved. So the solution in my case is to declare pointers to the types I needed instead of the types themselves. I thought I was being cheeky by declaring the variables of the type directly and avoiding memory management, but it backfired.

Top answer
1 of 5
7
You have three strings, and a pointer. You change which string the pointer points into three times. You do not change any of the strings.
2 of 5
1
Maybe it might help if you see your code as a compiler "sees it": Your code: char *myString = ""; myString = "Hello World"; myString = "Goodbye"; What a compiler would (essentially) do: char *myString = NULL; char datum1[] = "\0"; // same as "" myString = &datum1[0]; char datum2[] = "Hello World"; myString = &datum2[0]; char datum3[] = "Goodbye"; myString = &datum3[0]; In this way, you can see that what is happening "under the hood" is that you're just pointing to stack allocated char arrays that would go out of scope within a specific function. While you've basically already answered a lot of your own questions (i.e. understanding scope and undefined behavior), I will try and add some clarification to your concerns: so is C managing it in the background? No. At least not in the way a typical garbage collected language does. Instead it's using stack allocated memory that goes out of scope. Does C not manage it and therefore this is wrong? C isn't Java, C#, JavaScript, Python or any other language that operates in a VM (i.e. an interpreted language with garbage collection), so it's not wrong, but it's not right either because it's a misunderstanding of C works. What would happen if I now did myString=NULL;? Nothing that isn't already happening in that same code snippet; of course, outcomes are different if myString were an input or output parameter and you were to try and reference it in some way later on in your program out of scope of the assigning function. Would that leave allocated memory with no one pointing to it? No. See above about stack allocated memory. Lastly .. and I wouldn't need to do malloc, right? If you have a static variable, it lives in static program space within that translation unit; so no, you won't have to malloc. HOWEVER .... And now for the important question. In the previous example with the local int, what would happen if I assigned a global pointer the memory address of the local int when the function the int is local to ends? Since you're asking about pointers and local variables, and especially a static variable that is a pointer, if you were to do what you ask, that is, point a static variable to a variable within a local function, you get exactly what you know about: undefined behavior. To avoid the UB, instead of a pointer, you could just have a normal int. But if you do have a pointer, you would need to malloc that specific pointer so that it could point to memory that isn't stack allocated (and thus released when scope is gone); and then copy the data you want (e.g. with memcpy). Pointing to an invalidated memory location will likely result in a program crash (as it should) Using your own code as an example to illustrate (and slightly modified for better portability/proper syntax): #include #include #include int *globalPtr; // uninitialized at program start int someFunction() { int myLocalInt = 5; // don't do this if you've malloc'd // globalPtr = &myLocalInt; // since now globalPtr will point to a different memory location // and calling free will result in trying to free memory out of scope // instead do this: memcpy(globalPtr, &myLocalInt, sizeof(int)); printf("Of course this would print 5: %d\n",*globalPtr); return 0; } int main(int argc, char** argv) { globalPtr = malloc(sizeof(int)); // initialized memset(globalPtr, 0, sizeof(int)); // zero'ed out so not garbage data // note: you could avoid the memset by just doing this: // globalPtr = calloc(1, sizeof(int)); // notice its "c"alloc instead of "m"alloc someFunction(); printf("But what about now? Is it still 5? i=%d\n",*globalPtr); free(globalPtr); // don't forget to free what you allocated // note: strictly speaking, you don't *need* to free this basic // object since it's just an int, and when the program exits, any // objects in static program space will automatically be free'd, // but it's a best practice and something you *should* do, especially // for more complex objects that have handles to other things, like // sockets or files. return 0; }
🌐
LinuxQuestions.org
linuxquestions.org › questions › programming-9 › c-how-is-a-string-array-stored-in-memory-696673
C: How is a string array stored in memory?
Hello everyone, I need to call a function that takes a string array as argument, declared like this: Code: int someFunction(/* some parameters... */,
🌐
Reddit
reddit.com › r/cpp_questions › string literal in memory?
r/cpp_questions on Reddit: String literal in memory?
June 15, 2021 -

Hey,

const char * text = “test“;

how is a string literal stored? I once catched up, that it is stored in a constant memory section.

If i would define a function like this:

void foo(const char * text) { }

and then call this function infinitely with foo(“test“), does this can lead to memory overflow or something? Because the string i put in this function is stored everytime again and again, and so the memory would be full?

Or would this only be, if i put different strings in the function and call it infinitely?

Top answer
1 of 5
9
The way it works is something like this. The compiler takes the code const char * text = “test“; void foo(const char * text) { } foo(“test“); it will extract out the "test" and place that into some fixed part of memory - for example, it might put it at address 0x123. Then whenever it sees "test" it will replace it with that memory address (0x123). Those lines of code will become assembly looking very roughly like: const char * text = 0x123; void foo(const char * text) { } foo(0x123); If you call it infinitely, it will just keep on referencing the same bit of memory. There will be no overflow.
2 of 5
4
it is stored in a constant memory section. That is correct. It is stored somewhere in the readonly section of your binary. can lead to memory overflow or something? Overflow? No. Do out of bounds access? Depends on what your function does. It gets a pointer to the constant (null terminated) literal. Because the string i put in this function is stored everytime again and again, and so the memory would be full? It is not copied. You only pass the pointer to the global. Even if you call the function with the same literal more than once, the compiler will only put one copy of the literal in your binary. if i put different strings in the function and call it infinitely? Since nothing is copied, it will just have a constant (though infinite) memory footprint. Of course limitations of your OS apply, if the binary is too large, you have a problem. But it will have to be really big.
🌐
Emory
cs.emory.edu › ~cheung › Courses › 255 › Syllabus › 2-C-adv-data › SLIDES › a70.html
Strings in C
String = a sequence of characters · The C programming language does not have a String data type
Find elsewhere
🌐
CS UIC
cs.uic.edu › ~jbell › CourseNotes › C_Programming › CharacterStrings.html
C Programming Course Notes - Character Strings
The material in this page of notes ... the way some other languages such as C++ and Java do. Instead C stores strings of characters as arrays of chars, terminated by a null byte....
🌐
Quora
quora.com › Where-are-strings-stored-in-C
Where are strings stored in C? - Quora
Answer (1 of 3): One issue is the storage of string “constants” (aka literals). Consider: char *p; p = “hello there”; p[5] = ‘@’; it used to be that Unix/C would store the string in the data segment and it would be writable as data should be. However most would think that such data ...
Top answer
1 of 8
151

A common technique is for string literals to be put in "read-only-data" section which gets mapped into the process space as read-only (which is why you can't change it).

It does vary by platform. For example, simpler chip architectures may not support read-only memory segments so the data segment will be writable.

Rather than try to figure out a trick to make string literals changeable (it will be highly dependent on your platform and could change over time), just use arrays:

char foo[] = "...";

The compiler will arrange for the array to get initialized from the literal and you can modify the array.

2 of 8
85

Why should I not try to alter it?

Because it is undefined behavior. Quote from C99 N1256 draft 6.7.8/32 "Initialization":

EXAMPLE 8: The declaration

char s[] = "abc", t[3] = "abc";

defines "plain" char array objects s and t whose elements are initialized with character string literals.

This declaration is identical to

char s[] = { 'a', 'b', 'c', '\0' },
t[] = { 'a', 'b', 'c' };

The contents of the arrays are modifiable. On the other hand, the declaration

char *p = "abc";

defines p with type "pointer to char" and initializes it to point to an object with type "array of const char" with length 4 whose elements are initialized with a character string literal. If an attempt is made to use p to modify the contents of the array, the behavior is undefined.

Where do they go?

GCC 4.8 x86-64 ELF Ubuntu 14.04:

  • char s[]: stack
  • char *s:
    • .rodata section of the object file
    • the same segment where the .text section of the object file gets dumped, which has Read and Exec permissions, but not Write

Program:

#include <stdio.h>

int main() {
    char *s = "abc";
    printf("%s\n", s);
    return 0;
}

Compile and decompile:

gcc -ggdb -std=c99 -c main.c
objdump -Sr main.o

Output contains:

 char *s = "abc";
8:  48 c7 45 f8 00 00 00    movq   $0x0,-0x8(%rbp)
f:  00 
        c: R_X86_64_32S .rodata

So the string is stored in the .rodata section.

Then:

readelf -l a.out

Contains (simplified):

Program Headers:
  Type           Offset             VirtAddr           PhysAddr
                 FileSiz            MemSiz              Flags  Align
      [Requesting program interpreter: /lib64/ld-linux-x86-64.so.2]
  LOAD           0x0000000000000000 0x0000000000400000 0x0000000000400000
                 0x0000000000000704 0x0000000000000704  R E    200000

 Section to Segment mapping:
  Segment Sections...
   02     .text .rodata

This means that the default linker script dumps both .text and .rodata into a segment that can be executed but not modified (Flags = R E). Attempting to modify such a segment leads to a segfault in Linux.

If we do the same for char[]:

 char s[] = "abc";

we obtain:

17:   c7 45 f0 61 62 63 00    movl   $0x636261,-0x10(%rbp)

so it gets stored in the stack (relative to %rbp), and we can of course modify it.

🌐
Emory
cs.emory.edu › ~cheung › Courses › 255 › Syllabus › 2-C-adv-data › string.html
Strings in C --- arrays of char
string in C is stored as an · array of characters · Fact: Reason: Example: function with a · string variable · Example Program: (Demo above code) &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp ·
🌐
Quora
quora.com › How-are-strings-stored-in-C-Where-is-the-actual-text-stored
How are strings stored in C++? Where is the actual text stored? - Quora
Answer (1 of 2): “Text” in C++ is an array of [code ]char[/code] characters which is generally an ASCII integer but can be any of many different types of formats, such as UTF-8 , UTF-16, [code ]w_char[/code] (wide char) , etc. But basically it is an array of [code ]unsigned integer[/code] that ge...
🌐
TutorChase
tutorchase.com › answers › ib › computer-science › how-are-strings-stored-and-manipulated-in-memory
How are strings stored and manipulated in memory? | TutorChase
For instance, in languages like C and C++, a string is stored as an array of characters ending with a special character known as the null character. This character signals the end of the string.
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 127750-where-string-literals-store.html
where the "String literals" store in ?
EX: char string[50] = "liyanhong"; I konw 'string' will store in where called the Stack, but the String literals "liyanhong" where does it store ? The answer depends on where the array string[] is defined. If it's defined inside a function, then "liyanhong" will be stored in the stack segment.
🌐
Emory
mathcs.emory.edu › ~cheung › Courses › 255 › Syl-ARM › 2-C-adv-data › string.html
Emory
string in C is stored as an · array of characters · Fact: Reason: Example: function with a · string variable · Example Program: (Demo above code) &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp ·
🌐
Microsoft Learn
learn.microsoft.com › en-us › cpp › c-language › storage-of-string-literals
Storage of String Literals | Microsoft Learn
The characters of a literal string are stored in order at contiguous memory locations. An escape sequence (such as \\ or \") within a string literal counts as a single character. A null character (represented by the \0 escape sequence) is ...
🌐
Northern Illinois University
faculty.cs.niu.edu › ~mcmahon › CS241 › Notes › cstrings.html
C Strings
This is a somewhat advanced method ... program memory or runtime errors. ... The individual characters that make up the string are stored in the elements of the array....