I'm trying to create a 64 bit integer as class in C++, I know this already exists in the C header stdint.h but I thought it could be a fun challenge.
Anyway, I am trying to perform a bitwise XOR operation on three unsigned chars, and the program keeps stopping without warning, it just pauses for a split second and then stops:
unsigned char* a = (unsigned char*) 1;
unsigned char* b = (unsigned char*) 2;
unsigned char* c = (unsigned char*) 3;
unsigned char* result = (unsigned char*) malloc(sizeof(unsigned char));
std::cout << "Trying" << std::endl;
*result = *a ^ *b ^ *c;
std::cout << "Done!" << std::endl;
The output being:
PS C:\Users\super\Desktop> ./test.exe
Trying
PS C:\Users\super\Desktop>
I am using Windows 10 if that helps, let me know if you need any other information, and thanks for any help you can give me :)
You're trying to dereference invalid pointers. You want to get rid of a lot of those *
s.
unsigned char a = 1;
unsigned char b = 2;
unsigned char c = 3;
unsigned char* result = (unsigned char*) malloc(sizeof(unsigned char));
std::cout << "Trying" << std::endl;
*result = a ^ b ^ c;
std::cout << "Done!" << std::endl;
Why are you allocating a single byte (sizeof(unsigned char)
is 1
by definition) on the heap for the result? You could just make that another unsigned char
variable, too.
Editorial note: you also don't need to use std::endl
.