Web Analytics Made Easy -
StatCounter How to check if my program would run out of memory - CodingForum

Announcement

Collapse
No announcement yet.

How to check if my program would run out of memory

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to check if my program would run out of memory

    Hello,

    I had a school assignment to write a program, which is now past but I still don't understand how the whole thing should work. So I was asked to write a program in C to read a .txt file and display an error message if the program runs out of memory.

    So my question is can anyone show me an example of code which displays an error message if the program runs out of memory?

    Cheers

  • #2
    assuming you want the whole file in 1 go, get the size of the file, do an malloc, if it returned 0, you are out of memory

    Untested:

    PHP Code:
    #include <sys/stat.h>
    #include <string.h>
    #include <stdio.h>
    #include <errno.h>

    int filesize fsize(thefilename);

    if (
    filesize 1) {
       
    fprintf(stderr,"file does not exist or empty");
       exit (
    4);
    }

    char *buffer;
    buffer = (char *)malloc(filesize);

    if (
    buffer == 0) {
       
    fprintf(stderr,"out of memory");
       exit (
    4);
    }

    /* now you can read the file into the buffer */


    /* this little routine returns the size of the file */
    off_t fsize(const char *filename) {
        
    struct stat st;

        if (
    stat(filename, &st) == 0)
            return 
    st.st_size;

        
    fprintf(stderr"Cannot determine size of %s: %s\n",
                
    filenamestrerror(errno));

        return -
    1;

    Last edited by josephm; Sep 21, 2016, 01:38 AM.

    Comment


    • #3
      Still don't get the whole code, but thanks!

      Comment

      Working...
      X