I'm trying to gain a better intuition on how string literals work in C.
After the code segment above completes, what happens to the space in memory where the bytes making up the string "hello" are located? Does that space remain untouchable for the life of the program even though it's no longer accessible, or is it "freed up" the second I assign c = "goodbye"?Code:char * c = "hello"; c = "goodbye";
Also, what would the following code do?
Would it create space for "howdy" and then free it back up right after the statement completes? Are these string literals put into memory at compile time or run time? If it's compile time, does that mean it lives for the life of the program?Code:"howdy";
Similarly, when you write the statement "char c;" are those 30 bytes set aside at compile time or run time? What if the "char c;" was declared within a function. What happens when the function completes (and c no longer exists?)? Are the 30 bytes ever "freed up", or are they just sitting there, unable to be used for the rest of the program?
Finally, the following code produces a seg-fault when I run it and enter a single-character string for input, and I'm trying to understand why.
My current understanding of the above code segment is this: a pointer to a character is declared and given the name c. The base address of the string "hello" is then assigned to c. When I run this, I enter the string "a" as my input, which scanf writes to the location specified by c, which is the base address of "hello". So why does this give me a seg-fault? Shouldn't I be able to input any string that is the same size or smaller than the string "hello"? What am I not thinking about correctly?Code:char * c = "hello"; scanf( "%s", c );
Also, in the above example (which was only constructed for learning purposes) for a real program I would replace the "char * c = "hello";" with "char c;". Is this the way it's usually done if you're just inputting a string?
I'm very confused. However many questions you feel like answering, I'm grateful.