Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers and dynamically allocated arrays in C++

Tags:

c++

I'm trying to get this clear up in my mind.

int* arrayA = new int[3];
int arrayB[3] = {1,2,3}

arrayA = arrayB;

Does the value of arrayB get copied over to arrayA? Or does arrayA become a pointer to arrayB?

like image 420
user103052 Avatar asked Sep 24 '13 07:09

user103052


3 Answers

Naked new is evil, especially for arrays. Use std::vector if you need dynamic array and std::array if you need static one.1

Now the actual answer is simple. arrayA is a pointer. So it's made to point to arrayB. That has additional effect that:

  1. you now leaked the allocated pointer.
  2. attempt to delete arrayA will now crash or something else unpleasant, because you would be trying to free unallocated memory.

Actually while C++ allows assigning structures and classes, it does not support assigning arrays at all. Unless part of an object either managed as in std::vector or as array member as in std::array (note: std::array is C++11).


1 The main reason is that the containers guarantee the resources will be released in their destructors, so called RAII idiom, avoiding most opportunities for memory leaks and dangling references.

like image 54
Jan Hudec Avatar answered Nov 11 '22 06:11

Jan Hudec


int* arrayA = new int[3];

arrayA now stores the address in memory of a different memory block thats large enough to contain 3 ints which is stored on the heap.

int arrayB[3] = {1,2,3};

arrayB is a block of memory thats large enough to contain 3 ints which is stored on the stack.

arrayA = arrayB;

Copies the address of the memory block that's stored on the stack into the variable arrayA. You have now lost the only reference to memory block stored on the heap, and have no way to free up the memory (a memory leak)

The memory stored on the stack and now pointed to by arrayA will not be safe to access when the current function returns. In particular returning arrayA (or arrayB) is not safe.

like image 29
Michael Shaw Avatar answered Nov 11 '22 08:11

Michael Shaw


For

Does the value of arrayB get copied over to arrayA?

Nope. It will not copy arrayB to arrayA. If you want to do so, you can do like,

for (int i=0;i<3;i++) arrayA[i]=arrayB[i]; //This is two arrays has same value

does arrayA become a pointer to arrayB?

Yes. It become a pointer to array of arrayB. After arrayA = arrayB; statement, memory allocated in the first line can not be accessible and it is a leak.

arrayA=arrayB; result in copying the address of arrayB to arrayA. arrayA will start pointing to the arrayB. Check it using,

printf("\n Base address of A[%u] base address of B[%u]", arrayA, arrayB);

Hope this helps.

like image 2
Saravanan Avatar answered Nov 11 '22 06:11

Saravanan