Jared
Jared

Reputation: 91

Dynamic memory allocation being overwritten?

I am having massive problems with my code. I do not understand why this is happening and having no idea how to fix it.

Basically I have tried to define an array of pointers to characters where each element of the array of pointers stores a different set of characters.

Class constructor: (note: size is an integer which specifies how large my array of pointers should be, the user can define this)

storeElements = new char*[size]; 

Say the size = 3, now storeElements should be an array of pointers capable of pointing to 3 separate strings of characters.

*storeElements = "one"; 
*(storeElements+1) = "two"; 
*(storeElements+2) = "three"; 

When I print these values straight after assigning them, they print the correct strings, however later on in my code, in other functions and after many other variables have been declared, and I have opened an output text file, *storeElements kind of gets muddled up.

Say for example, if I tried to do this (later on in my code):

cout << *(storeElements+2) << endl;

Instead of printing "three" it might print "one" or nothing at all.

There has got to be a problem with dynamic memory allocation here because I am reading from text files and sometimes the contents of that text file gets stored in the elements of *storeElements without me assigning them to *storeElements at all

Please help me better understand how to fix this. I've invested a lot of time and effort into my code and am very upset over this. Thank you for taking the time out of your day to help me.

Upvotes: 3

Views: 1798

Answers (1)

Pooja Nilangekar
Pooja Nilangekar

Reputation: 1479

It's simple, you have allocated memory for the pointers, however you haven't allocated memory for the char arrays that they pointers point to.

This line of code is perfect.

storeElements = new char*[size]; 

Now if you look at this line of code:

*storeElements = "one"; 

You haven't allocated any memory to store "one". What you should so is allocate memory before you assign the values. Something like:

*storeElements = new char[strlen("one")+1];
strcpy_s(storeElements[0], strlen("one")+1, "one");

Upvotes: 2

Related Questions