Access to infinite array elements? [duplicate] - c++

This question already has answers here:
Accessing an array out of bounds gives no error, why?
(18 answers)
Closed 6 years ago.
I try to understand pointers. Question is: should'nt I get a segmentation fault when compiling the second for loop? If no why not? I could not prevent any access to elements which are outside of y[0][dim].
int main(){
int dim = 3;
int ordnung = 2;
double** y = new double*[ordnung];
for(int i = 0; i<ordnung; i++){
y[i] = new double[dim];
}
for(int i = 0; i<=100; i++){
cout << y[0][i] << endl;
}
delete[] y;
return 0;
}
The output is also confusing me:
0
0
0
1.63042e-332
0
0
0
6.520933e-319
and ongoing zeros. What does that mean?

When you allocate memory using new[], it doesn't initialize the memory in any specific way. Its content is indeterminate and accessing it, even for reading, leads to undefined behavior.
You also go out of bounds of the allocated memory which also leads undefined behavior. C++ have no built-in bounds-checking.
And then you don't free all the memory you allocate. For each new there should be a matching delete, and for every new[] a matching delete[].
Lastly a few notes: First of all if you ever think you need a dynamic array, then your next thought should be std::vector.
And about the memory being uninitialized when using new or new[], that of course depends on what you allocate. If you allocate an object (or an array of objects) with a constructor, that will of course cause the constructor to be called. The constructor may, or may not, initialize the object.

Related

Is this a Segmentation fault or not? [duplicate]

This question already has answers here:
Undefined, unspecified and implementation-defined behavior
(9 answers)
Closed 2 years ago.
Is this a segmentation error or not? Why not? Please answer me, why this doesn't give me segmentation error?
#include <iostream>
using namespace std;
int main()
{
int ** T;
T = new int*[5];
for(size_t i=0; i<5; i++){
T[i] = new int[5];
}
T[4][7] = 10;
return 0;
}
Looks OK to me except for the 7 at the end. T is a pointer to pointer to ints, and it's assigned to an array of 5 pointers to ints (OK so far). Then each member of that array is assigned to a pointer to 5 ints. Still fine. Lastly, T[4] is a pointer to ints, but only 5 are assigned. So T[4][7] goes off the end of the array.
Now, will this actually segfault? That depends on memory alignment. If that address, &T[4][7] is on a different memory page than the actual allocated array, you'll get a segfault. Otherwise, you're just reading unallocated memory and you get whatever's there.

Deleting part of array not allowed, why? [duplicate]

This question already has answers here:
Can I delete[] a pointer that points into an allocated array, but not to the start of it?
(7 answers)
Why can't I delete pointer alone from an array of objects?
(4 answers)
Closed 5 years ago.
Consider, below program which gives runtime error. Point of this question is to understand memory view and management.
#include<iostream>
using namespace std;
int main(void) {
char* arr = new char[10];
char* ptr = NULL;
for(int i = 0; i < 10; i++) {
arr[i] = 'a';
}
cout << arr;
ptr = &arr[5];
delete ptr;
cout << arr;
return 0;
}
new allocates a block of memory. You can free that memory using delete, but you must pass the same address that was returned by new. That's how it works. You can't pass arbitrary addresses to delete.
Another option is to use malloc() and free(). These are older function but then you can also use realloc() to resize the memory. Then, if you want to delete part of the array, you can resize it to be smaller. BUT... you must still copy any data as needed to correctly form the resized array. That is not automatic.

C++ pointer array is still accessible after delete[] is called [duplicate]

This question already has answers here:
c++ delete pointer issue, can still access data [closed]
(6 answers)
C++ delete - It deletes my objects but I can still access the data?
(13 answers)
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 6 years ago.
In the following code, delete[] is called once to free up the memory allocated by new. However, the array elements is still accessible after delete[] is called. I called delete[] twice to confirm that I am getting a double free or corruption error, which I am getting, which means the memory is freed. If the memory is freed, how am I able to access the array elements? Could this be a security issue which might be exploited, if I am reading something like a password into the heap?
int *foo;
foo = new int[100];
for (int i = 0; i < 100; ++i) {
foo[i] = i+1;
}
cout << foo[90] << endl;
delete[] foo;
cout << foo[90] << endl;
gives the following output
91
91
and
int *foo;
foo = new int[100];
for (int i = 0; i < 100; ++i) {
foo[i] = i+1;
}
cout << foo[90] << endl;
delete[] foo;
delete[] foo;
cout << foo[90] << endl;
gives
*** Error in./a.out': double free or corruption (top): 0x000000000168d010 ***`
The memory is free, which means it isn't attributed anymore, but the compiler's not going to take the extra effort to wipe it back to 0 everytime something's deleted.
It's also not going to take the effort to check that the memory is properly allocated before you access it - it'd reduce performance, and it assumes you don't do so. (Although tools like valgrind or debuggers can detect those wrong calls)
So it just changes the range of the memory as 'unassigned' internally, which means another call to new can use that same memory range. Then whatever data in that memory would be overwritten, and foo[90] won't return the same thing anymore.

initializing char array in a function and returning it causes wrong outputs in main [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
char* func()
{
const int size = 24;
char bin[size];
char *temp;
for(int i=0; i<23; i++)
bin[i] = '1';
bin[23] = '\0';
temp = bin;
return temp;
}
int main()
{
char *s;
s = func();
cout << s << endl; //prints out weird values
return 0;
}
When compiled and ran, it print random values. In the function func, I initialized a char array and tried to return it. Upon returning it and printing it in main, it prints out weird values. What is wrong? Any help would be appreciated.
char bin[size];
allocate memory on the stack, you cannot refer to that location after the function returns: "char *s" is assigned a value that refer to an invalid memory location.
You must not use pointers to freed space, like the stack of a function which has finished executing.
This Undefined Behavior means anything goes, even the proverbial demons flying out of your nose.
Your choices:
Use a caller-allocated buffer.
Use a static buffer (beware reentrancy problems and multithreading woes).
Use dynamic allocation (new, new[], malloc() and friends).
return a struct (standard container or otherwise) containing the data. Might use dynamic allocation. (Last point courtesy of Matt McNabb).

How can I delete dynamic array pointer correctly [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C++ delete - It deletes my objects but I can still access the data?
Why doesn't delete destroy anything?
I've Created dynamic array, and I added values ​​to the values ​​of the array like that.
int *pArr;
pArr = new int[10];
for(int i=0;i<10;i++){
pArr[i] = i+2;
}
delete[] pArr;
// After deletion I can find the value of the array items.
cout << pArr[5] << endl;
As you see in the code above and in the last line, I can output the fifth element in the array without any problem .
With that supposed to be the array has been removed.
To show that the memory can be used again, consider this expansion of your code:
int *pArr;
pArr = new int[10];
for(int i=0;i<10;i++){
pArr[i] = i+2;
}
delete[] pArr;
int *pArr2;
pArr2 = new int[10];
for(int i=0;i<10;i++){
pArr2[i] = (2*i)+2;
}
cout << pArr[5] << endl;
That prints out 12 for me. i.e. the value from pArr2[5] actually. Or at least I should say it does for my machine with my specific compiler & version, etc. As others have pointed out it is undefined behaviour. But hopefully my example shows you at least one kind of undefined behaviour.
Once you delete[] the array and still try to access the elements of the array it is Undefined Behavior and any behavior is possible.
Yes, this may work, but is not guaranteed to work. Delete [] only invalidates the memory but does not zero it. The memory you are referencing is invalidate at this point. So don't do it :)
You did delete it correctly.
Then, you invoked Undefined Behaviour and found the memory still existed(*) and wasn't zeroed - a tool like valgrind would still show it as a bug though, which it is.
(*) By "still existed" I mean "is accessible to the process" - it could contain anything, but happens not to have been overwritten ... yet.