Code:
#include <stdio.h>
int main() {
char *str;
char i = 'a';
str = &i;
str = "Hello";
printf("%s, %c, %x, %x", str, i, str, &i);
return 0;
}
I get this output:
Hello, a, 403064, 28ff0b
I have following two doubts:
How can I store a string without allocating any memory for it.
str
is a character pointer and is pointing to where char variablei
. When I addstr = "Hello";
aren't I using5
bytes from that location4
of which are not allocated?Since, I code
str = &i;
shouldn'tstr
and&i
have same value when I printf them? When I remove thestr = "Hello";
statementstr
and&i
are same. And ifstr
and&i
are same then I believe when I saystr = "Hello"
it should overwrite'a'
with'H'
and the rest'ello\0'
come into the subsequent bytes.I believe the whole problem is with
str = "Hello"
statement. It doesn't seem to be working like what I think.
Please someone explain how it works??
The compiler writes the sequence of bytes { 'H', 'E', 'L', 'L', 'O', '\0' } in a section of the executable called the data segment.
When the application runs, it takes the address of these bytes and stores them in the variable representing 'str'.
It doesn't have to "allocate" memory in the sense that, at run time, the program does not have to ask the OS for memory to store the text.
You should try to avoid treating string literals like this as non-const. GCC's "-Wall" option promotes assignment of string literals to "char*" pointers as
Many compilers, when compiling with optimization, will do something called "string pooling", which avoids duplicating strings.
If compiled with string pooling, the executable might only contain one instance of "hello".