C/C++语言-指针和算术..异常代码:c0000005

C/C++ language - POINTERS and ARITHMETIC... Exception Code: c0000005

本文关键字:异常 代码 c0000005 C++ 语言 指针      更新时间:2023-10-16

下面的代码编译正确,但在执行时,控制台显示以下错误。。。异常代码:c0000005。错误发生在以下行:

*cptr++ = hextbl[((tval >> 4) & 0x0F)];

此错误是由于对内存的访问不正确。这样,我相信这个错误可能是我仍然在做的事情不正确理解指针和算术。。。

#include <stdio.h>
// function prototypes
int main(int argc, const char *argv[]);
char *put_hexbyte(char *cptr, char tval);
// main routine
int main(int argc, const char *argv[]) // variables to get arguments
{
    char val = 65;     // 0x41 >>> I need 2 bytes 0x34 and 0x31,
                       // they are ASCII from 0x41 (0x34 = "4" and 0x31 = "1")
    char *bufASCII;    // pointer to store these ASCII
    bufASCII = put_hexbyte(bufASCII, val);
    return 0;
}

// Put a byte as hex ASCII, return pointer to next location.
char *put_hexbyte(char *cptr, char tval) 
{
    static char hextbl[16] =
    {
        '0', '1', '2', '3', '4', '5', '6', '7',
        '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
    };
    printf("at this point, all is OK!!!n"); // <<< OK!
    *cptr++ = hextbl[((tval >> 4) & 0x0F)];  // <<< memory violation error! (Exception Code: c0000005)
    *cptr++ = hextbl[tval & 0x0F];
    return(cptr);
}

谢谢你的帮助!:)

您的指针:

char *bufASCII;

未初始化。然后你写信给它:

*cptr++ = x;

您需要先初始化它,否则使用它是未定义的行为。例如:

char *bufASCII = new char[2];

尽管即使在那时,这:

bufASCII = put_hexbyte(bufASCII, val);

会丢失对原始指针的跟踪。如果您想要缓冲区末尾的返回值,您应该存储该分隔符l:

char* eob = put_hexbyte(bufASCII, val);

这:

char *bufASCII;    // pointer to store these ASCII

是一个指向字符的指针,但它实际上还没有指向任何东西,因此您不能写入该指针。