[英]Qt/C++ Exited with code -1073741819 (Program crashes with exception code c0000005)
[英]C/C++ language - POINTERS and ARITHMETIC… Exception Code: c0000005
下面的代碼已正確編譯,但是在執行時,控制台將顯示以下錯誤...異常代碼: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);
會丟失您的原始指針。 如果要返回緩沖區結尾的值,則應存儲該分隔符:
char* eob = put_hexbyte(bufASCII, val);
這個:
char *bufASCII; // pointer to store these ASCII
是指向字符的指針,但實際上它尚未指向任何內容,因此您無法寫入該指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.