Thread: Using malloc

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    2

    Using malloc

    I have two programs written in C. Why does the first program work without malloc, but the second one doesn't unless I use malloc?

    Code:
    int main(){
    char * word;
    word = "abcde";
    printf("You entered: %s\n", word );
    }
    


    Code:
    int main(){
    char * word;
    strcpy(word, "abcde");
    printf("You entered: %s\n", word );
    }

  2. #2
    Registered User
    Join Date
    Jan 2009
    Location
    Australia
    Posts
    375
    "abcde" exists in memory in both programs as a string literal.

    In the first program you are making the 'word' pointer point at "abcde" (or the address at which it resides). Nothing wrong with this, just know that you can't modify the string because it's in read only memory.

    In the second program you are trying to copy "abcde" in to the memory pointed to by the 'word' pointer. You haven't initialised the 'word' pointer so it's pointing at some garbage value and you aren't allowed to write there.

    malloc will create some memory for you to use for your 'word' pointer, thus allowing you to copy the string into it.

  3. #3
    Registered User
    Join Date
    Feb 2013
    Posts
    2
    Thank you for the quick and helpful answer.

  4. #4
    Registered User
    Join Date
    Feb 2013
    Posts
    2
    In the first bit, where you say

    word = "abcde";

    "abcde" exists. When you declare that literal, memory is reserved for it. Think of when you call printf. You give it a string literal, so what's actually happening is: memory is reserved, the string literal is placed there, and printf gets a pointer to it. So the point is: making a string literal reserves memory in an implicit way.

    When you use strcopy, it modifies the memory where word points to. If you recall the pointer basics, word can point anywhere at all. Unfortunately for you, there is no rule that says it has to point somewhere that's yours. The memory it points to could be in use, by some other program or something. Making a pointer does not reserve memory. You have to direct to reserved memory. So if you set it equal to a string literal, it points to the literal which has it's own reserved memory, but by actually copying it, you are not changing where the pointer points, but rather moving the memory to the place. It's like instead of pointing at a lighthouse, you move the lighthouse in front of your finger.


  5. #5
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    If you really want to mix things up, try this.
    Code:
    #include <string.h>
    #include <stdio.h>
    
    int main()
    {
         char *word;
         word = "ABCDCE";
         strcpy(word, "abcde");
         printf("You entered: %s\n", word );
    }
    This code attempts to modify the string literal "ABCDE", and then print it.

    Note that I've #include'd headers to prevent the compiler from applying default assumptions about what strcpy() and printf() do (and to prevent warnings from modern compilers).

    The result is undefined. Modifying a string literal is actually not permitted. However, with most C compilers, it will compile - and possibly crash when executed. Some C compilers will give a warning (about the assignment "word = "ABCDE"") but most won't. With C++ compilers, the code is more likely to elicit a warning, since the conversion (of a string literal to a non-const char pointer) is deprecated.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  6. #6
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Quote Originally Posted by username1 View Post
    Why does the first program work without malloc, but the second one doesn't unless I use malloc?
    To make your second program work without malloc, you can write it like this:

    Code:
    int main(){
        char word[6];
        strcpy(word, "abcde");
        printf("You entered: %s\n", word );
    }
    The 6 means that 6 bytes are allocated at compile time, which is enough to hold strings which have a strlen of 5 or less.

    Quite often, the number 6 (N) is known, but you don't know how big the strings will be. Then it's better to use strncpy to avoid undefined behavior.

    Code:
    #define WORD argv[1]
    #define N 6
    int main(int argc, char *argv[]){
        if (argc != 2) {
            printf("Usage: printword WORD\n");
            exit(EXIT_SUCCESS);
        }
    
        char word[N];
        if (strncpy(word, WORD, N)[N-1] != '\0') {
            printf("Sorry, that word is too long. Program will abort.\n");
            exit(EXIT_FAILURE);
        }
            
        printf("You entered: %s\n", word);
        exit(EXIT_SUCCESS);
    }
    With strncpy, the character at position N-1 is guaranteed to be '\0' if the string "fits". Therefore, if it is not '\0' you know that it was too big.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 05-19-2010, 02:12 AM
  2. Replies: 7
    Last Post: 10-01-2008, 07:45 PM
  3. malloc
    By complicato in forum C Programming
    Replies: 1
    Last Post: 04-20-2008, 12:36 AM
  4. Why use malloc()
    By I-See-C in forum C Programming
    Replies: 30
    Last Post: 11-27-2007, 04:44 AM
  5. What does malloc() do?
    By manwhoonlyeats in forum C Programming
    Replies: 43
    Last Post: 12-12-2002, 02:18 AM