C中的异常阅读位置

时间:2017-08-04 11:43:11

标签: c autocad objectarx

我有一个简单的C代码如下:

#pragma warning(disable : 4996)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <process.h>
#include <math.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <windows.h>

#include <tchar.h>
int main()
{
    int ndsc;
    char *line = ' ';
    FILE *fd;
    int  x;
    wchar_t path[256];

    wcscpy(path, L"C:/");

    //wcscat(path, L"common\\descr.txt", wcslen(L"common\\descr.txt"));
    //Previous
    wcscat(path, L"common/descr.txt");



    if ((fd = _wfopen(path, L"r")) == NULL)
    {
        printf("Can't open %s for reading.\n", path);
        return 1;
    }
    for (ndsc = 0; fgetws((wchar_t*)line, 80, fd) != NULL; ndsc++)
    {
        x = wcslen((const wchar_t*)line);
        printf("Length of %d line is %d\n", ndsc, x);
    }
    fclose(fd);
    return 0;
}

我正在尝试从C:\ Common目录中读取名为descr.txt的文件。但是在for循环中它会抛出未处理的异常,如下所示:

Unable to read memory

Exception

有人可以解释我为什么会收到此错误以及如何解决。 顺便说一下,此代码在AutoCad的.arx文件中使用。我刚刚提取了抛出错误的部分,并尝试将其作为VS 2015 Update 3中的独立项目运行。此代码是.NET调用的.C文件的一部分。即使在.arx(从AutoCad点击所需菜单)的上下文中执行也会得到相同的异常。

先谢谢。

4 个答案:

答案 0 :(得分:4)

此处:char *line = ' ';您将char分配给char *

稍后您尝试使用宽字符串缓冲区。您需要wchar_t line[80]实际为80 wchar_t分配空间。

答案 1 :(得分:1)

变量line是一个指针,它指向地址32(使用ASCII编码)。

该地址几乎不是写入输入字符串的有效地址。

你需要让它指向一个足够大的内存,以适应你读取的整个字符串(包括终结符)。或者让它成为阵列。

由于指针不正确,您将有未定义的行为,这会使您的整个程序格式错误并且无效。

此外,你需要在fgetsw的调用中强制另一个标志,表明你做错了,而且使用了错误的类型(char代替wchar_t)。

答案 2 :(得分:0)

Line是一个指向某些非法地址的指针,这些地址来自&#39;的ascii代码的int值。 &#39 ;.

而不是char *line = ' ';

制作它(如果你想让行成为一个字符数组)

 char line[80 * sizeof(wchar_t)];

答案 3 :(得分:0)

You arre trying to assign a char to a char * by using simple quotes.

If you want to directly assign an int or a char to a char *, use double quotes (" "), or, if it is a single char, you might want to proceed as follows:

char line[0] = ' ';

Make sure that your pointer has been malloc'd and it should do the trick.

A string of digits can later be re-converted to an int using atoi() if you want.