1

Since the number of elements is determined by some conditions, I wrote a program like this;

 int i = 0; int *layer; while (i != 12){ layer = new int; layer[i] = i; cout << layer[i] << endl; i++; } delete[] layer; return 0; 
I get the result;
 0 1 2 3 4 5 6 
And then program crashes. What is the reason of this and how should I modify the program in order to allocate memory for unknown number of elements? Thanks in advance!

1 Answer 1

1

You have undefined behaviour. You allocate space for a single int, then you treat it as an array.

layer = new int; // single int layer[i] = i; // wat?? 

Then you leak the memory, then you call delete[] on the last newed int. Since it isn't clear what you want to do with your code, I can only offer some suggestions:

  • Consider using std::vector<int> as a dynamic array. It will save you a lot of trouble.
  • If you must allocate an array with new (you probably don't), you need new int[n] where n is the number of elements.
  • Call delete [] for every new[] and delete for every new.
Sign up to request clarification or add additional context in comments.

2 Comments

Okey, I may use vector but is there a way to allocate memory for next one at each time?
You can either create a vector with a given size, or push_back elements into it, increasing its size by one each time.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.