MrPickle5
MrPickle5

Reputation: 522

Dynamic memory allocation giving access violation(s)

My code keeps breaking (i.e. throwing me an access violation exception) when I allocate room for a buffer in my hex array.

I declare the hex array as a two star pointer in main and pass it in by reference.

Somewhere in main.cpp

char ** hexArray = nullptr;

Somewhere in fileio.cpp

void TranslateFile(char * byteArray, char **& hexArray, int numberOfBytes, char buffer[])
{
int temp = 0;

//Convert bytes into hexadecimal
for(int i = 0; i < numberOfBytes; i++)
{
    //Convert byteArray to decimal
     atoi(&byteArray[i]);

     //Set temp equal to byteArray
     temp = byteArray[i];

     //Convert temp to hexadecimal and store it in hex array
     itoa(temp, buffer, 16);

     //Allocate room for buffer
     hexArray[i] = new char[strlen(buffer) + 1]; //CODE BREAKS HERE

     //Copy buffer into newly allocated spot
     strcpy(hexArray[i], buffer);
}
}

Upvotes: 1

Views: 682

Answers (5)

c.fogelklou
c.fogelklou

Reputation: 1801

char ** is either an array of char * or is a pointer to a char *. Either way, you need to allocate something before you can do hexArray[i].

somewhere in main.cpp:

hexArray = new char *[NUM_CHAR_PTRS];

Later...

hexArray[i] = new char[strlen(buffer) + 1];

Upvotes: 1

Brian Cain
Brian Cain

Reputation: 14619

Have numberOfBytes entries in hexArray already been allocated?

Use strnlen instead of strlen or better still std::string. Do you know whether buffer is terminated or not (that is, is it part of TranslateFile's contract)?

Upvotes: 0

Summer_More_More_Tea
Summer_More_More_Tea

Reputation: 13466

You don't allocate space for the hexArray itself. What you done in

 //Allocate room for buffer
 hexArray[i] = new char[strlen(buffer) + 1]; //CODE BREAKS HERE

is allocating memory for elements of the hexArray.

So you should put the code:

hexArray = new char*[numberOfBytes];

before entering the for loop.

Upvotes: 1

Brandon
Brandon

Reputation: 39222

You need to allocate memory for the outer array. From your example, it is probably:

hexArray = new char *[numberOfBytes];

Upvotes: 1

Ed Swangren
Ed Swangren

Reputation: 124800

char ** hexArray = nullptr;

hexArray is uninitialized.

hexArray[i] = new char[strlen(buffer) + 1]; //CODE BREAKS HERE

You dereference hexArray, but it is uninitialized, and thus your program yields undefined behavior. You need to initialize it and, per your code sample, it must point to at least numberOfBytes elements.

hexArray = new char *[numberOfBytes];

Now hexArray is an initialized pointer which points to numberOfBytes uninitialized pointers.

Upvotes: 3

Related Questions