Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Where are the errors? This won\'t run.... Thank you for your time. // Amount of

ID: 3676989 • Letter: W

Question

Where are the errors? This won't run.... Thank you for your time.

// Amount of memory
buf = sample("meminfo", 1, 4);
printf("Memmory line: %s ", buf);
sscanf(buf, "%d%d%d", &tot_mem, &used_mem, &avail_mem);
free(buf);
printf("Total memory: %d ", tot_mem);
// Amount of memory currently available
printf("Unallocated memory: %d ", avail_mem);
// Load averages
/*****/
for(i=0; i<end_time; i+=incr_time) {
buf = sample("loadavg", 0, 0);
printf("Load avg %s ", buf);
free(buf);
sleep(incr_time);
}

return(0);
}


char *sample(char *fileName, const int lineNo, const int charNo)
{
char ch;
char pathName[MAX_PATHNAME] = "/proc/";
char *buf;
int i, j;
FILE *fid;

strcat(pathName, fileName);
fid = fopen(pathName, "r");
for(i = 0; i < lineNo; i++)
for(j=0; ;j++) {
ch = getc(fid); // Span leading lines
if(ch == ' ') break;
}
for(i = 0; i < charNo; i++) ch = getc(fid); // Span leading chars
i = 0;
ch = '';
buf = (char *) malloc(MAX_BUF_LINE);
while(ch != ' ') {
ch = getc(fid);
buf[i++] = ch;
}
buf[i-1] = '';
close(fid);
return buf;
}

Explanation / Answer

Errors are rectified:

#include<stdio.h>
#include<time.h>
#include <unistd.h>

void main()
{
   char* buf;
   int tot_mem,used_mem,avail_mem,end_time,incr_time,i;
// Amount of memory
    buf = sample("meminfo", 1, 4);
    printf("Memmory line: %s ", buf);
    sscanf(buf, "%d%d%d", &tot_mem, &used_mem, &avail_mem);
    free(buf);
    printf("Total memory: %d ", tot_mem);
// Amount of memory currently available
    printf("Unallocated memory: %d ", avail_mem);
// Load averages
/*****/
    for(i=0; i<end_time; i+=incr_time) {
        buf = sample("loadavg", 0, 0);
        printf("Load avg %s ", buf);
        free(buf);
        sleep(incr_time);
    }

    return(0);
}


char *sample(char *fileName, const int lineNo, const int charNo)
{
    char ch;
    const int MAX_PATHNAME=10,MAX_BUF_LINE=10;
    char pathName[MAX_PATHNAME] = "/proc/";
    char *buf;
    int i, j;
    FILE *fid;

    strcat(pathName, fileName);
    fid = fopen(pathName, "r");
    for(i = 0; i < lineNo; i++)
        for(j=0; ;j++) {
            ch = getc(fid);    // Span leading lines
            if(ch == ' ') break;
        }
    for(i = 0; i < charNo; i++) ch = getc(fid);    // Span leading chars
    i = 0;
    ch = '';
    buf = (char *) malloc(MAX_BUF_LINE);
    while(ch != ' ') {
        ch = getc(fid);
        buf[i++] = ch;
    }
    buf[i-1] = '';
    close(fid);
    return buf;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote