How to add value to pointer to array - c++

I have 2 arrays of char in int, to count symbols in text. I definitely have to use char and int, no map.
int* counterCPU = new int[256]{ 0 };
char *cstrCPU = new char[book.length() + 1];
strcpy(cstrCPU, book.c_str());
CountCPURealisation(cstrCPU, counterCPU);
void CountCPURealisation(char* book, int* counter)
{
int lenght = strlen(book);
for (int i = 0; i < lenght; i++) {
counter[book[i]]++;
}
}
but when I try to run the code, i got an error:
0xC0000005: Access violation reading location
For this line: counter[book[i]]++;
I tried to use & instead of * but it didnt work. Hate c++, could you point me out to an error?

Related

Error: Initialization with '{...}' expected for aggregate object

below is my code which processes the payload[] array and store it's result on myFinalShellcode[] array.
#include <windows.h>
#include <stdio.h>
unsigned char payload[] = { 0xf0,0xe8,0xc8,0x00,0x00,0x00,0x41,0x51,0x41,0x50,0x52,0x51,0x56,0x48,0x31 };
constexpr int length = 891;
constexpr int number_of_chunks = 5;
constexpr int chunk_size = length / number_of_chunks;
constexpr int remaining_bytes = length % number_of_chunks;
constexpr int size_after = length * 2;
unsigned char* restore_original(unsigned char* high_ent_payload)
{
constexpr int payload_size = (size_after + 1) / 2;
unsigned char low_entropy_payload_holder[size_after] = { 0 };
memcpy_s(low_entropy_payload_holder, sizeof low_entropy_payload_holder, high_ent_payload, size_after);
unsigned char restored_payload[payload_size] = { 0 };
int offset_payload_after = 0;
int offset_payload = 0;
for (size_t i = 0; i < number_of_chunks; i++)
{
for (size_t j = 0; j < chunk_size; j++)
{
restored_payload[offset_payload] = low_entropy_payload_holder[offset_payload_after];
offset_payload_after++;
offset_payload++;
}
for (size_t k = 0; k < chunk_size; k++)
{
offset_payload_after++;
}
}
if (remaining_bytes)
{
for (size_t i = 0; i < sizeof remaining_bytes; i++)
{
restored_payload[offset_payload++] = high_ent_payload[offset_payload_after++];
}
}
return restored_payload;
}
int main() {
unsigned char shellcode[] = restore_original(payload);
}
I get the following error on the last code line (inside main function):
Error: Initialization with '{...}' expected for aggregate object
I tried to change anything on the array itself (seems like they might be the problem). I would highly appreciate your help as this is a part of my personal research :)
In order to initialize an array defined with [], you must supply a list of values enclosed with {}, exactly as the error message says.
E.g.:
unsigned char shellcode[] = {1,2,3};
You can change shellcode to be a pointer if you want to assign it the output from restore_original:
unsigned char* shellcode = restore_original(payload);
Update:
As you can see in #heapunderrun's comment, there is another problem in your code. restore_original returns a pointer to a local variable, which is not valid when the function returns (a dangling pointer).
In order to fix this, restore_original should allocate memory on the heap using new. This allocation has to be freed eventually, when you are done with shellcode.
However - although you can make it work this way, I highly recomend you to use std::vector for dynamic arrays allocated on the heap. It will save you the need to manually manage the memory allocations/deallocations, as well as other advantages.
You can't assign a char * to a char []. You can probably do something with constexpr but I'm suspecting an XY problem here.

Access pointers stored in multimap -C++

I am maintaining a multimap to store pointer variables, code compiles fine but throws exception. please review my code below and provide suggestion
multimap<const char*, int **> myMap1;
int *myVals = new int[3];
myVals[0] = 1;
myVals[1] = 1;
myVals[2] = 1;
myMap1.insert(pair<const char*, int **>("val1", &myVals));
std::multimap<const char*, int **>::iterator it = myMap1.find("val1");
int *storedVals = reinterpret_cast<int *>(it->second);
for(int ii = 0; ii< 2; ii++)
{
printf("\n Value %d", storedVals[ii]); //Exception thrown here..
}
delete myVals;
You should update your code as below, and refer to this link if you wanna know why.
multimap<const char*, int **> myMap1;
int *myVals = new int[3];
myVals[0] = 1;
myVals[1] = 1;
myVals[2] = 1;
char * temp = "val1";
myMap1.insert(pair<const char*, int **>(temp, &myVals));
std::multimap<const char*, int **>::iterator it = myMap1.find(temp);
int *storedVals = *(it->second);
for(int ii = 0; ii<= 2; ii++)
{
printf("\n Value %d", storedVals[ii]); //Exception thrown here..
}
delete [] myVals;
Also prefer to use auto it for iterators instead of std::multimap<const char*, int **>::iterator it. Also you cant use 'reinterpret_cast' here.
I am not sure of the reason why you are using a reinterpret_cast here:
Your value (second) in the map is holding a pointer to a int*
If you change this line with the following. It would work:
int *storedVals = *(it->second); //it->second is a int**
Also you should not do myVals[2] = 1; your array size is 2. Alternatively you can increase the size of your array to 3.

Segmentation Fault Error On Basic Array Operation

The following code is throwing Segmentation fault (core dumped) error when I run it. The code is compiled with g++
struct SomeClass {
int *available;
int **need;
int **allocation;
}
SomeClass::SomeClass(int nR, int nT) {
available = new int[nR];
for (int i = 0; i < nR; i++) {
available[i] = 1;
}
*allocation = new int[nT];
*need = new int[nT];
for (int i = 0; i < nT; i++) {
allocation[i] = new int[nR];
need[i] = new int[nR];
for (int j = 0; j < nR; j++) {
allocation[i][j] = 0;
need[i][j] = 1; // should equal 1
}
}
}
Am I sure that this code is generating the error? YES! Because I commented it out and everything works fine.
I checked this question:
A segmentation fault error with 2D array
The answer says to set the stack size ulimit -s unlimited... But that didn't fix the problem.
Because your types are:
int **need;
int **allocation;
these lines:
*allocation = new int[nT]; // dereferencing uninitialized pointer
*need = new int[nT];
should be:
allocation = new int*[nT]; // proper allocation
need = new int*[nT];
Didn't you think you'd need elements of int* type for allocation[i] = new int[nR]; to work?
I strongly suggest (and strongly feel deja vu) to move away from an attempt to emulate 2-D arrays with pointers to pointers. It is hard to do this right. Pack all your values into single-dimensional array.

Can't delete an unsigned char* after inserting data

I have this code
unsigned char _binary[] = {'1','1','1','0','0','0','1','0',NULL};
int length = 0;
for(length=0;_binary[length];length++);
unsigned char *_hexaActual = new unsigned char;
ConvertBinaryToHexaDecimal(_binary, length, _hexaActual);
string _actual((char*)_hexaActual);
delete[] _hexaActual; // crashes here
Now the ConvertBinaryToHexaDecimal is
void ConvertBinaryToHexaDecimal(const unsigned char* _inputBinary, unsigned int _intputLength, unsigned char* _outputHexaDecimal)
{
const unsigned char _hexaDecimalSymbols[16] = {'0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F'};
char* _binary =(char*) malloc(sizeof(char));
int _binaryIndex,_inputIndex;
for(_binaryIndex=0; _binaryIndex < _intputLength%4 ;_binaryIndex++) // padding extra 0's to make the length multiple of 4
_binary[_binaryIndex] = '0';
for(_inputIndex=0; _inputIndex < _intputLength ;_inputIndex++)
_binary[_inputIndex + _binaryIndex] = _inputBinary[_inputIndex];
_binary[_inputIndex + _binaryIndex] = NULL;
_intputLength = _inputIndex + _binaryIndex;
for( _inputIndex=0; _inputIndex < _intputLength; _inputIndex +=4)
{
int _binaryValue = _binary[_inputIndex] - 48;
int _binaryValue1 = _binary[_inputIndex+1] - 48;
int _binaryValue2 = _binary[_inputIndex+2] - 48;
int _binaryValue3 = _binary[_inputIndex+3] - 48;
int _hexValue = _binaryValue3 * 1;
_hexValue += _binaryValue2 * 2;
_hexValue += _binaryValue1 * 4;
_hexValue += _binaryValue * 8;
_outputHexaDecimal[_inputIndex/4] = _hexaDecimalSymbols[_hexValue];
}
_outputHexaDecimal[_inputIndex/4] = NULL;
}
It outputs corretly a hexa decimal value. But when I try to delete it the program crashes.
EDIT: The crash message says HEAP CORRUPTION DETECTED.
You allocated a single unsigned char with new, so you should call delete, not delete []. The latter is for arrays allocated with new [].
You need
delete _hexaActual;
Note that this type of manual allocations and de-allocations are error prone and exception unsafe. It is likely that you can implement your code using standard library containers and algorithms.
Edit: besides that error, you have a few more: The most important one, in the function ConvertBinaryToHexaDecimal, you are passing a pointer to a single unsigned char, but you are treating it like an array:
_outputHexaDecimal[_inputIndex/4] = ....
Next, you hve a memory leak. You allocate here:
char* _binary =(char*) malloc(sizeof(char));
and never call free.
You only allocated one char for _hexaActual, but you are writing many values to it inside ConvertBinaryToHexaDecimal. You need allocate enough space for the characters you are going to put in there. length/4 + 2 should do it.
unsigned char *_hexaActual = new unsigned char[length/4 + 2];

What does access violation mean?

I'm new to C++ and do not understand why I am getting the error "Access Violation Reading Location". Here is my code:
gdiscreen();
int startX = 1823 - minusX;
int startY = 915 - minusY;
for (int i = startX; i < startX + 61; i++)
{
for (int j = startY; j < startY + 70; j++)
{
Color pixelColor;
bitmap->GetPixel(i, j, &pixelColor);
cout << pixelColor.GetValue() << " ";
}
cout << endl;
}
gdiscreen() can be found here:
http://forums.codeguru.com/showthread.php?476912-GDI-screenshot-save-to-JPG
Access violation or segmentation fault means that your program tried to access a memory that was not reserved in the scope.
Have a few examples how to achieve this:
Leaving bounds of array:
int arr[10];
for(unsigned char i=0; i<=10; i++) //Will throw this error at i=10
arr[i]=0;
Note: In the code above, I use unsigned char to iterate. Char is one byte, so unsigned char is 0-255. For larger numbers, you may need unsigned short (2 bytes) or unsigned int (4 bytes).
Accidentally calculating with pointer instead of integer
int ah = 10;
int *pointer = &ah; //For some reason, we need pointer
pointer++; //We should've written this: (*pointer)++ to iterate value, not the pointer
std::cout<<"My number:"<<*pointer<<'\n'; //Error - accessing ints address+1
I intentionally started with broad explanation. You wanted to know what access violation is at the first place. In your particular code, I'm very sure you messed up with i and j boundaries. Do some std::cout debug.