I asked this question in a c community and someone replied that it is
related to virtual addressing.
How it is related to virtual addressing?
Firstly, please ignore the trolls in this group. The 4095 figure is
entirely theoretical. In practice on all current real-world compilers,
string literals can be as big as you want - the only limitation is the
amount of memory available to store them.
Unfortunately, there are a group of people who seek to disrupt this
group by treating all questions as if they are about an abstract machine
that they call the "Death Station", which behaves completely differently
to any machine that actually exists. On the "Death Station", you can
only have one string literal and its length can be no more than 4095. No
real machine behaves like this.
What is the connection with virtual addresses?
Well, the kernel provides each process with a virtual address space, and
takes responsibility for mapping this to physical memory. When your C
program has been loaded and starts executing, the operating system
(executable-loader) has kindly set up this address space to look like
this:
highest address
=========
| |
| |
| |
| |
| |
| |
=========
| data |
| +bss |
=========
| text |
=========
address 0
As your program starts generating stack frames and automatic variables,
the stack grows downwards from high to low memory addresses. Meanwhile,
the heap starts growing upwards from above the data segment.
highest address
=========
| stack |
| vv |
| |
| |
| ^^ |
| heap |
=========
| data |
| +bss |
=========
| text |
=========
address 0
Things get more interesting when you add libraries, threads etc. into
the mix, but this is the basic setup.
Now the data (= data + bss) segment, which sits below the stack, is the
relevant part here. In particular, the data area in the data segment
contains your program's global variables that aren't initialized to zero
- this is where your string literals will live!
Typically, there will be separate read only and read/write data areas. A
string literal like "hello" in
if(strcmp(s, "hello") == 0)
can be placed in the read only area, whereas a global character array
like
char s[] = "hello";
has to be read/write under C rules.
The effect of virtual memory is that string literals can be as big as
you want subject to available physical memory - the 4095 figure is just
a red herring.