I was trying to define an array in c++
double array[592];
I made a mistake and used "sizeof" command instead of size to limit a loop which printed the elements one by one. Hence, the loop was reading array indices until index 4736. Although these locations do not exist, I was getting garbage instead of segmentation fault for all locations after 592. I'm wondering why I'm not getting segmentation fault.
sizeof gives you the number of bytes the array occupies, not the number of elements it consists of. So as a double requires 8 bytes on your system, the result should become clear.
sizeof(array) // Returns 592 * sizeof(double)
Gives you the total number of bytes occupied by an array.
Related
I have declare array with large size 10^5 in local function which gave me run time error, but when I took vector instead of an array the code was successful.
so why do vector does not gave error while array did??
Have a look here this explains the difference between local variables (stack) and dynamically allocated memory (which std::vector uses)
https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/
It would be better if you provide the code snippet. But I can assume that you are create your array on the stack wich has size limit(usually up to few MB or even less than 1 MB).
Vector on the other hand allocate memory on the heap wich is usually much more than size of the stack.
So because heap size is sufficient to contain 10^5 byte you don't have an error when using vector. And because stack size is not enough to contain 10^5 byte you get a runtime error when using array.
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.
My code takes an int input and sets that as the array's size, and I have some test prints that print out the index of the array starting from 0 to 4..
std::cout<<array[0]<<std::endl;
std::cout<<array[1]<<std::endl;
std::cout<<array[2]<<std::endl;
std::cout<<array[3]<<std::endl;
std::cout<<array[4]<<std::endl;
However, I noticed that if the input is smaller than 5, say 2 for instance, then the first two cout print out correctly, but then the rest print out 0 or random numbers like 17 and 135137. Is this an out of bounds thing that happens when you index beyond the array size or is this a problem in my code? (I know I have to change the print statements)
The arrays are dynamically allocated by the way, which I think shouldn't matter.
Is this an out of bounds thing that happens when you index beyond the array size or is this a problem in my code?
Both.
Assuming array itself has a size of at least 5 elements, the initial contents of it before you set the values to anything are undefined; essentially random (they're just whatever happened to be hanging out in that particular block of memory that your array now occupies). If array itself has a size of less than 5, the values are still undefined but accessing them also runs the risk of crashing the program. In either case, the fact that you are printing values beyond the end of the initialized, valid data in your array is a problem with your code.
If you allocate an array of n elements, accessing the (n+1)th element is undefined behaviour (UB). (Note after comments: The (n+1)th element is the element with index n. So if array has only size 3, accessing array[3] already causes UB).
So, yes it is an "out of bounds thing" and it is a problem of your code (because it's you who accesses the array beyond its size.
Why not loop to print out simply the existing element instead of hardcoding the indices?
Would like to know in C++ what the value of unassigned integer in an int[] usually is.
Example
int arr[5];
arr[1]=2;
arr[3]=4;
for(int i=0;i<5;i++)
{
cout <<arr[i] <<endl;
}
it print
-858993460
2
-858993460
4
-858993460
we know that the array will be {?,2,?,4,?} ,where ? is unknown.
What will the "?" be usually?
When I tested , I always got negative value.
Can I assume in C++ unassigned element in the integer array is always less than or equal to zero?
Correct me if I'm wrong. When I study in Java unassigned element in array will produce null.
Formally, in most cases the very attempt to read an uninitialized value results in undefined behavior. So, formally the question about the actual value is rather moot: you are not allowed to even look at that value directly.
Practically, uninitialized values in C and C++ are unpredictable. On top of that they are not supposed to be stable, meaning that reading the same uninitialized value several times is not guaranteed to read the same value.
If you need a pre-initialized local array, declare it with an explicit initializer
int arr[5] = {};
The above is guaranteed to fill the array with integer zeros.
When I tested , I always got negative value.
The (previously) unused memory space seemed filled with the hex code 0xCC. However, as mentioned above -- several times -- you cannot rely on this.
In one of your comments you clarify your task:
im trying to create an int array let say of the size 100 and randomly insert postive integer into any position in the array. If the array is not full. how could i determine if that position in the array has never been assigned[?]
Fill the array with zeros (manually, or per AndrewT's answer). Since you are inserting positive integers only, all you have to test for is !0.
You can't know what this will produce, since it takes as value the bits that are in memory in that moment. So you can get ANY value, not only negative values.
The values contained in an unitialized area of memory can be anything, it is implementation depending. The most efficient implementation is to leave the memory as it was, so you will find in your array whatever was contained before. An important note: it is not something you can use as a random value. Some implementation (I have seen that, especially in the past, when compiling and running in debug mode) might put zeros in your memory, but it is uncommon. You simply should not rely on the content of uninitialized area of memory.
To understand if something has not been touched in your array, you can initialize it to some value like DEADBEEF:
http://en.wikipedia.org/wiki/Hexspeak
(Unless you are so unlucky that one of the values you have to insert corresponds exactly to DEADBEEF... :) )
These are garbage values, you cannot expect to work with these variables properly and they will not predict what it may result into. Whenever a variable gets allocated some portion of memory gets allocated for that variable and those portion may be used previously for some other unknown calculation which you cannot know, so you have to intialize those variables with some values to avoid usage of garbage values.
You are not assigning any value at these locations. So it will return garbage values from memory. You must put some values at these locations. Unimplemented locations will returned in some unexpected/unpredictable values.
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").