Looking for malloc() help

Discussion in 'C Programming' started by SP, Aug 3, 2006.

  1. SP

    SP Guest

    I am learning C and have a question re: malloc().

    I wrote simple program which assigns a value to a structure and then
    prints it as follow:

    #include <stdio.h>
    #include <stdlib.h>

    struct item {
    char name[20];
    int quantity;

    int main (int argc, char *argv[])
    struct item *stuff;

    //allocate memory for structure
    stuff = malloc(3 * sizeof(struct item));

    strcpy(stuff[1].name, "apple");
    stuff[1].quantity = 1;
    strcpy(stuff[2].name, "banana");
    stuff[2].quantity = 2;

    printf("%s %d\n", stuff[1].name, st.quantity);
    printf("%s %d\n", stuff[2].name, st.quantity);

    return 0;

    I then change the structure declaration in order to dynamically
    allocate memory
    for the char array:
    struct item {
    char *name;
    int quantity;

    The program compiles with no errors, but it crashes with the following

    line 3: 2485 Segmentation fault

    Thanks for your help
    SP, Aug 3, 2006
    1. Advertisements

  2. SP

    xiaohuamao Guest

    I don't know what is the problem. The following code works in my
    struct item {
    char* name;
    int quantity;

    int main ()
    struct item *stuff;

    //allocate memory for structure
    stuff = (struct item *)malloc(3 * sizeof(struct item));

    stuff[1].name = (char *) malloc(sizeof("apple"));
    strcpy(stuff[1].name, "apple");
    stuff[1].quantity = 1;
    stuff[2].name = (char *) malloc(sizeof("banana"));
    strcpy(stuff[2].name, "banana");
    stuff[2].quantity = 2;

    printf("%s %d\n", stuff[1].name, stuff[1].quantity);
    printf("%s %d\n", stuff[2].name, stuff[2].quantity);

    return 0;
    xiaohuamao, Aug 3, 2006
    1. Advertisements

  3. SP

    SP Guest

    Not sure it matters, my PC is as follows:

    Linux Slackware 10.1
    compiling program with "gcc -o test struct.c"

    Is anyone else able to run this ?
    SP, Aug 3, 2006
  4. st has not been defined. You probably mean stuff[1].quantity
    In the first case the struct contains memory (20 bytes) for storing the
    names so the malloc() for the structs is sufficient. In the second
    case the struct contains only a pointer, so you are copying "apple" to
    whatever random address ends up in stuff[1].name. Undefined behaviour.

    You could either use malloc() to allocate space for storing the name
    and assign the resulting pointer to stuff[1].name, or just do
    stuff[1].name = "apple";
    and not copy the string at all.

    In this case just assigning the pointer would make more sense, but in a
    real example either strategy might be appropriate.


    [*] Technically the undefined behaviour could be even worse than
    copying to some random address, but that's bad enough.
    Thomas Lumley, Aug 3, 2006
  5. So you've shown us the program that works, but not the one that

    Ok, I'll assume that the change in the declaration of "struct item"
    was the only change you made. The problem is that you haven't
    allocated space for the strings "apple" and "banana". You need
    to do something like:

    stuff[1].name = malloc(some_number_of_bytes);
    strcpy(stuff[1].name, "apple");

    Some other notes:

    If you don't use argc and argv, you can omit their declarations:
    int main(void)

    Always check the result of malloc(). If it fails for whatever reason,
    you go on and try to access the memory anyway; this can Make Bad
    Things Happen. Even if you just abort the program on failure, it's
    better than ignoring it.

    Your malloc() call is good, but there's a little trick that can make
    it even better:

    stuff = malloc(3 * sizeof *stuff);

    This way, you don't have to repeat (and possibly get wrong) the type
    of "stuff" in the malloc call, and if you change the type of stuff you
    don't have to track down and change all the calls.

    I presume you know you're using only the 2nd and 3rd of the 3 elements
    you allocated for your array.

    It's generally considered a good idea to avoid "//" comments when
    posting to Usenet. News software often wraps long lines. If a "//"
    comment is wrapped, it usually creates a syntax error; if a "/*
    .... */" comment is wrapped, it's usually harmless. (And "//" comments
    aren't supported in C90.)
    Keith Thompson, Aug 3, 2006
  6. SP said:
    Not bad, but better would be:

    stuff = malloc(3 * sizeof *stuff); /* note the * in front of stuff */

    because there's less to get wrong (you don't need to type the typename, so
    you can't mess it up - not that you did, on this occasion), and it's more
    robust in the face of subsequent changes to the pointer type.

    But malloc can fail. In that eventuality, it will return NULL. You should
    check for this before relying on the allocation.

    For a "student exercise" such as this one, the following would be

    if(stuff == NULL)
    fputs("Insufficient memory to continue. Terminating program.\n",
    You're not using stuff[0], then? Well, okay, it's your memory...
    That's fine, apart from what I've pointed out already.
    Yes. Now that you've changed name from being an array to being a mere
    pointer, you need to point it at some storage.

    if(stuff != NULL)
    int i;
    for(i = 0; i < 3; i++)
    stuff.name = malloc(20 * sizeof *stuff.name);
    if(stuff.name == NULL)
    fprintf(stderr, "Can't allocate space for name %d\n", i);
    fprintf(stderr, "Terminating program.\n");

    You will now be able to do your strcpy in safety (provided the string you
    copy into it is 19 or fewer bytes long).

    Once you've finished, and before you free(stuff), you should do this:

    for(i = 0; i < 3; i++)

    Then you can free(stuff);
    Richard Heathfield, Aug 3, 2006
  7. Thomas Lumley said:
    Well spotted. I missed those completely.
    Richard Heathfield, Aug 3, 2006
  8. SP

    SP Guest

    Allocating memory for the char array was the part I didnt know how to
    now it works just fine.

    Thanks to all.
    SP, Aug 3, 2006
  9. Never ever cast the result from malloc() except you like to go into
    the lands of undefined behavior and you dont like to get diagnostics
    from your compiler when you've forget to include stdlib.h.

    Never ever cast something - excet you knows exactly what you're
    doing. casting the result of a function returning void* is playing
    with the health of y<or app because you does NOT know what you does.
    When you would know what you does you would never cast that.
    see above
    see aboove
    Before you frees stuff you should free its members you've allocated
    with malloc() to avoid memory leaks.

    Array starts with index 0, not 1. Why does you malloc 3 struct members
    when you only needs 2? And why does you use the last but not the first


    Visit http://www.ecomstation.de the home of german eComStation
    eComStation 1.2 Deutsch ist da!
    Herbert Rosenau, Aug 4, 2006
  10. No, you've forgotten to include stdlib.h so even as it seems to work
    you're sitting in the middle of the lands of undefined behavior.


    Visit http://www.ecomstation.de the home of german eComStation
    eComStation 1.2 Deutsch ist da!
    Herbert Rosenau, Aug 4, 2006
  11. SP

    Guest Guest

    Or if you want C++ compatibility, for whatever reason. (It may not make
    sense for most C code, but one of the times it does make sense is if
    it's an inline function in a header file that's kept after
    You can quite legitimately cast a void * return value if you want to
    store it as an (u)intptr_t value.

    I wouldn't have commented if you hadn't so specifically said "never".
    Guest, Aug 4, 2006
  12. SP

    Joe Wright Guest

    But you didn't allocate the memory. You'll need something like..

    stuff[1].name = malloc(20);


    strcpy(stuff[1].name, "apple");

    ...and then you must free stuff[1].name (and stuff[2].name) before
    freeing stuff.
    Joe Wright, Aug 5, 2006
  13. No. In C++ you would use simply operator new.
    You can burn your home, no question. Bit is it a good idea to do so?
    You can kill your wife too. Casting is insidious and casing void* to
    anything else says nothing but you knows not how to handle pointers to
    It is simply: never ever cast the result of a function returning a
    pointer to void. You'll end up in the lands of undifined behavior..


    Visit http://www.ecomstation.de the home of german eComStation
    eComStation 1.2 Deutsch ist da!
    Herbert Rosenau, Aug 6, 2006
  14. SP

    Guest Guest

    new is not an option when writing header files that work both for C and
    for C++ code.
    How would you use (u)intptr_t, then? (If you say you wouldn't at all,
    keep in mind that it's a type defined in standard C(99).)
    That's clearly untrue, and depending on your intent quite possibly a
    lie. There's no undefined behaviour in casting the result of malloc().
    It's usually poor style, and it can cover up warnings when the
    behaviour would be just as undefined without a cast, but that's all.
    Guest, Aug 6, 2006
  15. But you says that it is good to write programs for both C anf FORTRAN
    or C++ and Cobol?

    You can't write a single program that uses two highly different
    languages. When you needs to write failsave programs instead of
    hacking blind around you have to use either C or C++. Mixing up
    languages inside the same program ends always up with holes of any
    I would use it as it is defined. Conversion between all kinds of data
    pointer to/from pointer to void is done already witrhout cast. When
    you does not know what you does you should avoid cats anyway.
    You must learn C before you can use the language, so start learning C.
    Until you have learned C you are absolutely unable to something about
    the language. You've proven now that you knows nothing about C.

    Will you guarantee that in each and any environment a function
    returning a pointer uses always the same location as a function
    returning int, even as the standard since more than 15 years says the

    You knows nothing about C but tells nonsense. There are more traps you
    falls in as you can dream of when you does not understund what C is -
    and you have not even basic knowlede about C yet.


    Visit http://www.ecomstation.de the home of german eComStation
    eComStation 1.2 Deutsch ist da!
    Herbert Rosenau, Aug 6, 2006
  16. No, he didn't say that.
    C and C++ are not "highly different"; C is nearly (but not exactly) a
    subset of C++, and it's possible to write reasonable code within the
    intersection of the two languages.

    It rarely makes sense to do so. 99% of the time, it makes more sense
    to write in pure C, or to write in pure C++, or to use C++'s 'extern
    "C"' mechanism if you need to use both. But it's also possible to
    write library code that's intended to be used by either C or C++
    client code. P.J. Plauger does this, for example.
    Keith Thompson, Aug 6, 2006
  17. Keith Thompson said:

    And the reason his name is always given as an example is that he's almost
    the only guy in the universe with a good reason to do this.
    Richard Heathfield, Aug 6, 2006
  18. SP

    Guest Guest

    It is impossible in standard C to store a pointer value in an
    (u)intptr_t object without a cast. Using a cast in this case, according
    to you, shows you don't know how to handle pointers. So I ask again,
    how would you use (u)intptr_t?
    No, that's clearly untrue, no disagreement there, but where is the
    undefined behaviour in this program?

    #include <stdlib.h>
    int main(void) {
    free( (char *) malloc(1) );

    What I said, if you would re-read my message, is that the cast itself
    does not invoke undefined behaviour. What does invoke undefined
    behaviour is giving an improper declaration of malloc(), but malloc()
    is properly declared here. A cast can happen to hide a diagnostic
    caused by an improper declaration, but the behaviour is not defined
    with or without it.
    Guest, Aug 6, 2006
  19. SP

    Ian Collins Guest

    Where did "programs' come from? The discussion was about headers.
    But they do (often) share headers.
    Ian Collins, Aug 7, 2006
  20. Please show us your code to store a void * in a uintptr_t without a
    Hmmm ...
    How's that relevant?
    You need to be on more solid ground than you are to make comments like
    these without looking foolish.
    J. J. Farrell, Aug 7, 2006
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.