Thread: how much to malloc for struct stat *

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    19

    how much to malloc for struct stat *

    The following seg faults eventually

    Code:
    #include <sys/stat.h>
    struct stat *fmt;
    
    fmt=malloc(sizeof(struct stat *));
    do{
      if(0!=stat(file,fmt)){
        printf("cannot watch the time stamp for the journal file\n");
        exit(1);
        }
      if(wait<MAX_WAIT) wait++;
      epoch=fmt->st_mtime;
      } while(old_epoch>epoch);
    free(fmt);
    If I replace the malloc line with

    Code:
    fmt=malloc(100+sizeof(struct stat *));
    seg faults goes away.

    What is the correct way to do this?

    Thanks

  2. #2
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    No need for malloc.

    Code:
    struct stat fmt;
    if (0 != stat(file, &fmt))
    {
       /* Handle error */
    }
    else
      epoch = fmt.st_mtime;

  3. #3
    Registered User
    Join Date
    Jun 2010
    Posts
    19
    That's much better. Thanks.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    If you really did want to use malloc, it should be:
    Code:
    fmt = malloc(sizeof(struct stat));
    or better yet:
    Code:
    fmt = malloc(sizeof(*fmt));
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling C in Visual Studio 2005
    By emanresu in forum C Programming
    Replies: 3
    Last Post: 11-16-2009, 04:25 AM
  2. Replies: 1
    Last Post: 09-06-2007, 04:17 AM
  3. Is there a limit on the number of malloc calls ?
    By krissy in forum Windows Programming
    Replies: 3
    Last Post: 03-19-2006, 12:26 PM
  4. Random Number Range Problem.
    By xamlit in forum C Programming
    Replies: 11
    Last Post: 01-26-2006, 12:55 PM
  5. malloc() & address allocation
    By santechz in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 09:08 AM