Thread: Why doesnt this malloc work please?

  1. #1
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154

    Why doesnt this malloc work please?

    Hi,

    Another malloc problem (the day I understand malloc you will all get a round of beer on me).

    Below is part of the code of a function for converting float values into floating point:
    Code:
    char* floating_point(float flt)
    {
       char *formula;
       
       formula = malloc(21);
    
       return formula;
    }
    The program exits without warning when it reaches the malloc line in the code above.

    To be complete, here is how I call the function:
    Code:
                        fa_string = floating_point(formula_a);
                        fprintf(fpout,"%s\n", fa_string);
                        free(fa_string);
    Pulling my hair out since 9am this morning (its 16:45h now). What is wrong here?

    Thanks for any help.


    René
    http://www.f1rstracing.nl/
    OS: Windows XP
    Compiler: Dev-C++

  2. #2
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    That looks like it will chrash in the next line: fprintf(fpout,"%s\n", fa_string);

    malloc(), does allocate 21 bytes for you, but those bytes contain random values. If you try to read them as a null terminating string, you may have to read past the end of the allocated space. This isn't supposed to work, and as a result your program crashes. Not sure why windows doesn't give an error message, but it happends. If you change your other code, then it might show the error message.

    There are many solutions, especially for integer types (including char, w_char, int, long, short).
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  3. #3
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154
    No it really crashes on that specific line, I've printed characters and getch(); after every code line and the malloc line is where it exited.
    http://www.f1rstracing.nl/
    OS: Windows XP
    Compiler: Dev-C++

  4. #4
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    I don't see anything wrong there. The only thing that could be done is

    Code:
    if(!(formula = malloc(21)))
    {
         ;//free up resources 
         if(!(formula = malloc(21)))
              exit(-1);
    }
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  5. #5
    Registered User SKeane's Avatar
    Join Date
    Sep 2006
    Location
    England
    Posts
    234
    Try

    Code:
    char* floating_point(float flt)
    {
       char *formula;
       
       formula = malloc(21);
    
       if ( formula == NULL) printf("malloc() failed\n");
       else strcpy(formula, "foobar");
    
       return formula;
    }
    See if it still fails in the same place. Go on, humour us.

  6. #6
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154
    Tried both of your suggestions, but in both cases it fails like it has done before...

    I will soon be left hair less.
    http://www.f1rstracing.nl/
    OS: Windows XP
    Compiler: Dev-C++

  7. #7
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154
    It does work when I run it in command prompt.... but only the first time... when I call the same function for the second time it exits like it did above....

    Any ideas?
    Last edited by rkooij; 10-06-2006 at 02:52 PM.
    http://www.f1rstracing.nl/
    OS: Windows XP
    Compiler: Dev-C++

  8. #8
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    > Below is part of the code of a function for converting float values into floating point:
    I simply do not understand what is going on because a floating point number is a floating point number. Are you trying to convert a number to string representation? Use snprintf with an empty string then and keep it simple:

    Code:
    size_t len = 21;
    char *str = malloc(len);
    if ( str )
    {
       int ret = snprintf(str, len, "%f", 3.14159f );
       if ( ret < len )
       { 
          puts(str);
          free(str);
       }
       /* else you need to resize the buffer */
    }
    Something like that.

  9. #9
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    You could use FLT_DIGITS (at least I think that's what it's called) to figure out how big your buffer needs to be. It's in <limits.h>.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  10. #10
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Quote Originally Posted by rkooij
    Below is part of the code of a function for converting float values into floating point:
    Code:
    char* floating_point(float flt)
    {
       char *formula;
       
       formula = malloc(21);
    
       return formula;
    }
    The program exits without warning when it reaches the malloc line in the code above.
    To me, this sounds like you had trashed your dynamic memory elsewhere in the code you didn't post, and you only discover this when you try a subsequent attempt at further dynamic allocation.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  11. #11
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154
    Quote Originally Posted by citizen
    I simply do not understand what is going on because a floating point number is a floating point number. Are you trying to convert a number to string representation? Use snprintf with an empty string then and keep it simple
    Quote Originally Posted by Dave_Sinkula
    To me, this sounds like you had trashed your dynamic memory elsewhere in the code you didn't post, and you only discover this when you try a subsequent attempt at further dynamic allocation.
    Here's the complete code of the function to make clear what I want it to do:

    Code:
    /******************************************************************************/
    char* floating_point(float flt)
    {
       char hex[9], hex_2[9], temp[3], *p;
       char *formula;
       int decimal[4], i=0, ii=0;
       short cnt=0, cnt2=0;
    
       union
       {
          unsigned long i;
          float f;
       }v;
    
    if(!(formula = malloc(21)))
    {
         free(formula);//free up resources 
         if(!(formula = malloc(21)))
              exit(-1);
    }
    
       v.f = flt;
       sprintf(hex_2,"%08lx",v.i);
       puts(hex_2);
    
       cnt=7;
       while(cnt2<=3)
       {
    
          sprintf(temp,"%c%c",hex_2[cnt-1],hex_2[cnt]);
          printf("%s\t",temp);
          decimal[cnt2] = strtol(temp,&p,16);
          cnt-=2;
          cnt2++;
       }
       printf("\n");
       sprintf(formula,"%d\t%d\t%d\t%d",decimal[0],decimal[1],decimal[2],decimal[3]);
       puts(formula);
    
       return formula;
    }
    /******************************************************************************/
    I hope this helps, as the problem still occurs...
    http://www.f1rstracing.nl/
    OS: Windows XP
    Compiler: Dev-C++

  12. #12
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154
    Edit: for heaven's sake, It seems to be working now... but I didnt change anything so I think it's a bit dodgy...
    Maybe it has to do with a memory leak, but I don't see where it's leaking?
    http://www.f1rstracing.nl/
    OS: Windows XP
    Compiler: Dev-C++

  13. #13
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    if(!(formula = malloc(21)))
    {
         free(formula);//free up resources 
         if(!(formula = malloc(21)))
              exit(-1);
    }
    If formula is NULL, because malloc just failed, why are you calling free on it?


    Quzah.
    Hope is the first step on the road to disappointment.

  14. #14
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154
    Quote Originally Posted by quzah
    Code:
    if(!(formula = malloc(21)))
    {
         free(formula);//free up resources 
         if(!(formula = malloc(21)))
              exit(-1);
    }
    If formula is NULL, because malloc just failed, why are you calling free on it?


    Quzah.
    Hmm don't know What else is meant with "free up resources" posted by King Mir somewhere above?
    http://www.f1rstracing.nl/
    OS: Windows XP
    Compiler: Dev-C++

  15. #15
    Registered User SKeane's Avatar
    Join Date
    Sep 2006
    Location
    England
    Posts
    234
    You can't "free" a resource if you don't have it in the first place.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  2. malloc and realloc
    By odysseus.lost in forum C Programming
    Replies: 3
    Last Post: 05-27-2005, 08:44 AM
  3. malloc() & address allocation
    By santechz in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 09:08 AM
  4. Problem with malloc() and sorting words from text file
    By goron350 in forum C Programming
    Replies: 11
    Last Post: 11-30-2004, 10:01 AM