How can I find the memory used by my array - c++

I have seen this asked in different forms, and I have been reading up on it, but I am still confused on how to find the memory used. I have an array it is being pointed to by a pointer the value *ptr = the number of elements in the array. I need the total size of the array and its elements (it is an array of short int and it has 14 elements total). I am confused on how to get this value of memory used by the array + memory used by the elements, would I just use size of and then add the two. This is where I keep running into issues. Can someone point me in the right direction?

To get the size in bytes of the array, you would have to calculate it using sizeof(short int) * number_of_elements, where number_of_elements is 14.

Instead of raw arrays, e.g., int ar[4], use std::array from <array>. Such array provides bounds checking for debug mode and, unlike raw arrays, can easily be copied and used as a function's argument. It also provides a size() method.

Related

C++ memcpy to end of an array

I'm trying to translate C++ into C# and I'm trying to understand, conceptually what the following piece of code does:
memcpy( pQuotes + iStart, pCurQuotes + iSrc, iNumQuotes * sizeof( Quotation ) );
pQuotes is declared: struct Quotation *pQuotes.
pCurQuotes is a CArray of struct Quoataion, iSrc being it's first index. iNumQuotes is the number of elements in pCurQuotes.
What I would like to know is, if iStart is to pQuotes' last index, would the size of pQuotes be increased to accommodate the number of elements in pCurQuotes? In other words, is this function resizing the array then appending to it?
Thanks.
SethMo
If iStart is to pQuotes' last index, would the size of pQuotes be
increased to accommodate the number of elements in pCurQuotes? In
other words, is this function resizing the array then appending to it?
No.
This is a fundamental limitation of these low-level memory functions. It is your responsibility as the developer to ensure that all buffers are big enough so that you never read or write outside the buffer.
Conceptually, what happens here is that the program will just copy the raw bytes from the source buffer into the destination buffer. It does not perform any bounds- or type-checking. For your problem of converting this to C# the second point is of particular importance, as there are no type conversions invoked during the copying.
would the size of pQuotes be increased to accommodate the number of elements in pCurQuotes?
No. The caller is expected to make sure before making a call to memcpy that pQuotes points to a block of memory sufficient to accommodate iStart+iNumQuotes elements of size sizeof(Quotation).
If you model this behavior with an array Quotation[] in C#, you need to extend the array to size at or above iStart+iNumQuotes elements.
If you are modeling it with List<Quotation>, you could call Add(...) in a loop, and let List<T> handle re-allocations for you.
No, memcpy does not do any resizing. pQuotes is merely a pointer to a space in memory, and the type of pointer determines its size for pointer arithmetic.
All that memcpy does is copy n bytes from a source to a destination. You need to apply some defensive programming techniques to ensure that you do not write beyond the size of your destination, because memcpy won't prevent it!

Dynamic and static array

I am studying C++ reading Stroustrup's book that in my opinion is not very clear in this topic (arrays). From what I have understood C++ has (like Delphi) two kind of arrays:
Static arrays that are declared like
int test[3] = {10,487,-22};
Dynamic arrays that are called vectors
std::vector<int> a;
a.push_back(10);
a.push_back(487);
a.push_back(-22);
I have already seen answers about this (and there were tons of lines and concepts inside) but they didn't clarify me the concept.
From what I have understood vectors consume more memory but they can change their size (dynamically, in fact). Arrays instead have a fixed size that is given at compile time.
In the chapter Stroustrup said that vectors are safe while arrays aren't, whithout explaining the reason. I trust him indeed, but why? Is the reason safety related to the location of the memory? (heap/stack)
I would like to know why I am using vectors if they are safe.
The reason arrays are unsafe is because of memory leaks.
If you declare a dynamic array
int * arr = new int[size]
and you don't do delete [] arr, then the memory remains uncleared and this is known as a memory leak. It should be noted, ANY time you use the word new in C++, there must be a delete somewhere in there to free that memory. If you use malloc(), then free() should be used.
http://ptolemy.eecs.berkeley.edu/ptolemyclassic/almagest/docs/prog/html/ptlang.doc7.html
It is also very easy to go out of bounds in an array, for example inserting a value in an index larger than its size -1. With a vector, you can push_back() as many elements as you want and the vector will resize automatically. If you have an array of size 15 and you try to say arr[18] = x,
Then you will get a segmentation fault. The program will compile, but will crash when it reaches a statement that puts it out of the array bounds.
In general when you have large code, arrays are used infrequently. Vectors are objectively superior in almost every way, and so using arrays becomes sort of pointless.
EDIT: As Paul McKenzie pointed out in the comments, going out of array bounds does not guarantee a segmentation fault, but rather is undefined behavior and is up to the compiler to determine what happens
Let us take the case of reading numbers from a file.
We don't know how many numbers are in the file.
To declare an array to hold the numbers, we need to know the capacity or quantity, which is unknown. We could pick a number like 64. If the file has more than 64 numbers, we start overwriting the array. If the file has fewer than 64 (like 16), we are wasting memory (by not using 48 slots). What we need is to dynamically adjust the size of the container (array).
To dynamically adjust the capacity of an array, a new larger array must be created, then elements copied and the old array deleted.
The std::vector will adjust its capacity as necessary. It handles the dynamic allocation of memory for you.
Another aspect is the passing of the container to a function. With an array, you need to pass the array and the capacity. With std::vector, you only need to pass the vector. The vector object can be queried about its capacity.
One Security I can see is that you can't access something in vector which is not there.
What I meant by that is , if you push_back only 4 elements and you try to access index 7 , then it will throw back an error. But in array that doesn't happen.
In short, it stops you from accessing corrupt data.
edit :
programmer has to compare the index with vector.size() to throw an error. and it doesn't happne automatically. One has to do it by himself/herself.

Point to 3dimensional array in c++

I have searched on google but only found answers for single-dimension arrays.
I have a 3 dimension array storing data to be later processed by a function.
My array looks like this : levelcode[400][20][100]. It stores all the info that the decode level function needs. I get an stack overflow error immediately.
But how can i point to the entire array to get the values of it ( or how do i pass down the entire array? ) ?
I know i can technically call the function for each existing parameter but i think it would be faster and it would look better if the entire array was passed down or being used using a pointer of some sort.
How can i accomplish this?
I suggest you use a std::vector. It is basically a self managed grow-able array. It stores the data dynamically(heap) so you will be using the full system memory instead of the small bit of memory the program is given for automatic objects(stack). With your levelcode[400][20][100] you have 800,000 elements. if the array is of type int then you would more than likely need 3.2MB of space for the array. typically this is larger than than the space provided to the program and will cause a stack overflow
I would suggest you use single dimension vector and then you can use math to fake the 3 dimensions. This will make the data more cache friendly as multi-dimensional vectors do not have to have each dimension located right next to each other like a multi-dimensional array does.
So instead of having a
std::vector<std::vector<std::vector<some_type>>> name{DIM1, vector<vector<some_type>>{DIM2, vector<some_type>{DIM3}}};
and using it like
name[x][y][z]
We could have a
std::vector<some_type> name{DIM1 * DIM2 * DIM3};
and then you can access the elements with
name[x*DIM2*DIM3 + y*DIM3 + z]

How can I discover the size/length(in bytes) of a std::vector?

I have a vector and I want to write and read it to a file but it is not possible to determine the logical size of a vector using the sizeof operator.
So what shall I do?
A c++ std::vector has a method size() which returns its size.
EDIT: as I get it now you need to compute the memory a given vector uses. You can't use sizeof for that as a vector uses dynamic memory and stores only a pointer of a dynamic array containing its elements. So my best suggestion would be to multiply the memory each element requires by the number of elements. Note this again will not work if the objects stores a pointer to some dynamically allocated objects - you will have again to compute their sizes separately.
There is no easy way to compute the memory a vector size in bytes in c++ that I know of.

C++ Calculating the number of bytes in an array of integers

This may or may not be a very simple question, but I would like to know what function to call in order to figure out how many bytes are in an array at any given time. For example, how would I know what to put as the third argument in the send command in the code below?
int *array= new int[500];
memset(array, 0, sizeof(array));
//newsockfd is declared elsewhere in the code
send(newsockfd, array, _______, 0);
The size of an array is constant (it's just a hunk of memory).
You'll need to keep track of how many elements of the array are valid yourself, in a separate variable.
As others have noted, the last argument to memset should be the number of bytes you want set to 0 -- but array is just a pointer, so sizeof(array) will yield only 4 (or 8 on a 64-bit platform). Again, you'll need to manually pass in sizeof(int) * 500 (or use a constant for the 500 so you don't have to update the number in multiple places if it changes).
There is no way that you can get count of items that dynamically allocated for an array, so the line memset(array, 0, sizeof(array)) do not fill 500 items in array with 0, and sizeof(array) is always equal to sizeof(int*), so if you want to have access to count of items that allocated for an array, you should either use a separate value that contain the size or use C++ storages like std::vector
Your memset() doesn't clear the dynamicly allocated memory new int[500], but just the first sizeof(int*) bytes.
If you want to clear the heap memory, do it this way:
memset(array, 0, 500 * sizeof(int));
or at initialization time:
int *array= new int[500]();
Also look at www.cplusplus.com/faq/sequences/arrays/sizeof-array/ is a good reading about the subject (not directly about the sizeof() operator but handling arrays in C++ in general, in a proper "C++ way").