【问题标题】:Unexpected Acess violation reading (tail)意外的访问冲突读取(尾)
【发布时间】:2016-12-30 18:39:00
【问题描述】:

这是我的尾部代码(前 10 行):

#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++));
}

我收到此错误:

访问冲突读取位置0x0000000000000000。

在这一行:

if (*lines[i]) {

我无法理解为什么。我希望有人能给我解释一下。

【问题讨论】:

  • space = mgetline(line, MAXLINESIZE) &gt; 0 --> (space = mgetline(line, MAXLINESIZE)) &gt; 0
  • if (*lines[i]) { --> if (lines[i]) {
  • @BLUEPIXY 第一条评论是有道理的。但是第二个没有意义?
  • @Stargateur 它在里面。
  • 抱歉,如果您将i++ 放入您的if 放入您的while,我重复一遍。只有if 中的条件为真,i 的值才会增加。因此,如果条件为假,您将永远不会增加 i,因此您将有一个无限循环。

标签: c access-violation tail


【解决方案1】:
while (space = mgetline(line, MAXLINESIZE) > 0)...

执行比较:

mgetline(line, MAXLINESIZE) > 0

并将结果(1 - 真或 0 - 假)存储在 space 中。

mgetline的结果存储到space,然后检查值是否大于0:

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

【讨论】:

  • 我正在用括号编辑问题。因为我仍然有错误。即使在这样做之后。无论如何,它值得 +1。
  • @Siliproksi 不要像破坏答案那样编辑您的答案。编辑只能添加信息而不是更改问题。
  • 是的,但这不是答案...我应该把问题留错吗?还是我应该接受错误的答案?即使我改变了这一点。我仍然遇到同样的错误。
  • @Siliproksi 你应该让问题错了,只是不接受这个答案。这不是问题。此答案为您提供了一个错误修复。如果这不能解决您所有的错误或您需要的任何东西。你不必接受它。你的 +1 就够了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-17
  • 2019-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多