-1

Here is my tail code (for first 10 lines):

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

typedef char storage_datatype;

#define MAXLINESIZE 1000
#define STORAGESIZE 10000
#define MAXLINES 100

int mgetline(char*, int);
char* alloc(int n);
void cp(char*, char*);

char *lines[MAXLINES];

storage_datatype storage[STORAGESIZE];
storage_datatype *storagep = storage;

int main(int argc, char **argv) {
    int space, i;
    space = i = 0;
    char line[MAXLINESIZE];
    char* p;
    while ((space = mgetline(line, MAXLINESIZE)) > 0) {
        p = alloc(space);
        cp(p, line);
        lines[i++] = p;
    }
    i = 0;
    while (i < 10) {
        if (*lines[i]) {
            printf("%s", lines[i++]);
        }
    }
    getchar();
    return 0;
}

int mgetline(char *s, int lim)
{
    int c;
    char *t = s;

    while (--lim > 0 && (c = getchar()) != EOF && c != '\n')
        *s++ = c;
    if (c == '\n')
        *s++ = c;

    *s = '\0';

    return s - t;
}

char* alloc(int n) {
    if (storage + STORAGESIZE - storagep >= n) {
        storagep += n;
        return storagep - n;
    }
    else
        return 0;
}

void cp(char *s, char *t) {
    while ((*s++ = *t++));
}

I am getting this error:

Access violation reading location 0x0000000000000000.

on this line:

if (*lines[i]) {

And i am not able to understand why. I hope someone can explain me this.

Siliproksi
  • 183
  • 9

1 Answers1

1
while (space = mgetline(line, MAXLINESIZE) > 0)...

performs the comparison:

mgetline(line, MAXLINESIZE) > 0

and stores the result (1 - true or 0 - false) in space.

To store the result of mgetline to space and then check if the value is larger then 0:

while ((space = mgetline(line, MAXLINESIZE)) > 0)...
Unimportant
  • 2,076
  • 14
  • 19
  • I am editing the question with the parantheses. Because i still have the bug. Even after doing that. Anyways it deserves +1. – Siliproksi Dec 30 '16 at 18:51
  • 1
    @Siliproksi Don't edit your answer like that you vandalize the answers. Edit must only add information not change the question. – Stargateur Dec 30 '16 at 18:53
  • Yes but this is not the answer... Should i leave the question wrong? Or should i accept the wrong answer? Even though i changed this. I still get the same bug. – Siliproksi Dec 30 '16 at 18:58
  • @Siliproksi You should let the question wrong and just not accept this answer. This is not a problem. This answer provides you one bug fix. If this doesn't fix all your bug or whatever you thing you need. You don't have to accept it. Your +1 is enough. – Stargateur Dec 30 '16 at 19:05