Thread: A few questions about string literals and inputting strings

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    12

    A few questions about string literals and inputting strings

    I'm trying to gain a better intuition on how string literals work in C.

    Code:
    char * c = "hello";
    
    c = "goodbye";
    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"?


    Also, what would the following code do?
    Code:
    "howdy";
    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?


    Similarly, when you write the statement "char c[30];" are those 30 bytes set aside at compile time or run time? What if the "char c[30];" 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.
    Code:
    char * c = "hello";
    
    scanf( "%s", c );
    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?

    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[100];". 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.
    Last edited by itsthemac; 03-27-2011 at 09:57 PM.

Popular pages Recent additions subscribe to a feed