Im a CS student, but I have some experience as a developer as well, which sometimes can make things more difficult, as demonstrated below.In my class my professor asked us to never use the following statement...
char* str = "Hello world";
According to the Professor...
"This is dangerous (and officially deprecated in the C standard) because you haven't allocated memory for str1 to point at."
I get that its bad, I don't care about that. The statement clearly demonstrates that I am failing to understand the way memory allocation works in regards to the C language. The statement can be ran, even if its deprecated, but I don't what I don't understand, is that if it is not allocating memory to the heap, it wouldn't make sense that it would allocate a variable initialization to the stack, which is where I get confused. Is there another area of memory, or like a cache that C uses specifically for local variable initialization? Where does the string Hello World get placed, and what address is assigned to the pointer in this case?
CodePudding user response:
The problem is in lvalue
and rvalue
. lvalue
defines locator value and it means that it has a specified place in memory and you can easily take it. rvalue
has undefined place in memory. For example, any int a = 5
has 5
as rvalue
. So you cannot take the address of an rvalue. When you try to access the memory for char* str = "Hello World"
with something like str[0] = 'x'
you will get an error Segmentation fault
which means you tried to get unaviable memory. Btw operators *
and &
are forbidden for rvalues
, it throws compile time error, if you try to use them.
CodePudding user response:
Summary:
"any strings in double quotes"
areconst lvalue string literals
, stored somewhere in compiled program.You can't modify such string, but you can store pointer to this string (of course const) and use it without modifying:
const char *str = "some string"
For example:
int my_strcmp(const char *str1, const char *str2) { ... } int main() { ... const char *rule2_str= "rule2"; // compare some strings if (my_strcmp(my_string, "rule1") == 0) std::cout << "Execute rule1" << std::endl; else if (my_strcmp(my_string, rule2_str) == 0) std::cout << "Execute rule2" << std::endl; ... }
If you want to modify string, you can copy string literal to your own array:
char array[] = "12323"
, then your array will ititialize as string with terminate zero at the end:Actually
char array[] = "123"
is same aschar array[] = {'1', '2', '3', '\0'}
.For example:
int main() { char my_string[] = "12345"; my_string[0] = 5; // correct! std::cout << my_string << std::endl; // 52345 }
Remember that then your array will be static, so you can't change it's size, for "dynamic sized" strings use
std::string
.