is there any probiem if we do malloc and free inside infinite while loop..?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jagadeesha
    New Member
    • Aug 2008
    • 4

    is there any probiem if we do malloc and free inside infinite while loop..?

    I am observing code is dumping at that point in the load. since we are allocating dynamically memory each time
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    Nothing wrong with an infinite loop that malloc's some memory, then frees it, then goes back to the top of the loop. If you don't free all the memory then you have a "memory leak" -- that is a problem regardless of whether you have an infinite loop.

    A core dump indicates a serious problem. Are you trapping the malloc error return (ie, when it returns NULL)?

    Comment

    • jagadeesha
      New Member
      • Aug 2008
      • 4

      #3
      i m not trapping... how to trap..?

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        With an if statement, test the return value of malloc.

        Comment

        • donbock
          Recognized Expert Top Contributor
          • Mar 2008
          • 2427

          #5
          Originally posted by jagadeesha
          i m not trapping... how to trap..?
          Code:
          foo_t *ptr;
          ptr = malloc(sizeof(foo_t));
          if (ptr == NULL) {
              printf("malloc failed!\n");
              exit(1);
              }
          Replace the printf/exit with whatever you think is an appropriate action to take when malloc fails.

          Comment

          Working...