This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is a stack overflow error?
look the code below.
#include <iostream>
using namespace std;
void leave(double as){
cout<<as;
leave(as);
}
int main(){
double x=1234.5;
leave(x);
cout<<"hellow";
}
When this code executes their is no way to stop. it should print the value x over and over again. But practically, this works for about 20 secs and close automatically. It doesn't print the line hellow. What is the reason for it? In windows task manager I can realize that the memory used with the application will increase. but I have allocated memory for x within the main function only, so will the function allocate memory for x over and over again. Is this type of situation called a memory leak? if its so what lines should be added to prevent it?
If I change the code as below it shows the word hellow without going through the function over and over again:
void leave(){
leave();
}
int main(){
leave();
cout<<"hellow";
}
How to explain these situations?
Every call to leave() results in adding a little information to the stack. When you call it recursively, the stack grows until it runs out of space, and the operating system terminates the application. In the second example, presumably the compiler optimized out the function that did nothing.
Related
This question already has answers here:
Why is it that we can write outside of bounds in C?
(7 answers)
Is accessing a global array outside its bound undefined behavior?
(8 answers)
Undefined, unspecified and implementation-defined behavior
(9 answers)
Closed 11 months ago.
I wrote a code for entering element and displaying the array at the same time. The code works but since char A[4] is static memory why does not it terminate/throw error after entering more than four elements? Code:
#include <iostream>
using namespace std;
void display(char arr[],int n)
{
for(int i=0; i<n; i++)
cout<<arr[i]<<" ";
return;
}
int main()
{
char A[4];
int i=0;
char c;
for(;;)
{
cout<<"Enter an element (enter p to end): ";
cin>>c;
if(c=='p')
break;
A[i]=c;
i++;
display(A,i);
system("clear");
}
return 0;
}
Writing outside of an array by using an index that is negative or too big is "undefined behavior" and that doesn't mean that the program will halt with an error.
Undefined behavior means that anything can happen and the most dangerous form this can take (and it happens often) is that nothing happens; i.e. the program seems to be "working" anyway.
However maybe that later, possibly one million instructions executed later, a perfectly good and valid section of code will behave in absurd ways.
The C++ language has been designed around the idea that performance is extremely important and that programmers make no mistakes; therefore the runtime doesn't waste time checking if array indexes are correct (what's the point if the programmers never use invalid ones? it's just a waste of time).
If you write outside of an array what normally happens is that you're overwriting other things in bad ways, possibly breaking complex data structures containing pointers or other indexes that later will trigger strange behaviors. This in turn will get more code to do even crazier things and finally, some code will do something that is so bad that even the OS (that doesn't know what the program wants to do) can tell the operation is nonsense (for example because you're trying to write outside the whole address space that was given to the process) and kills your program (segfault).
Inspecting where the segfault is coming from unfortunately will only reveal what was the last victim in which the code is correct but that was using a data structure that was corrupted by others, not the first offender.
Just don't make mistakes, ok? :-)
The code works but since char A[4] is static memory why does not it terminate/throw error after entering more than four elements?
The code has a bug. It will not work correctly until you fix the bug. It really is that simple.
This question already has answers here:
Accessing an array out of bounds gives no error, why?
(18 answers)
Closed 2 years ago.
I have written a small program but couldn't understand why it does't crash when a is accessed out of bounds?
#include <iostream>
using namespace std;
int main()
{
double *a = new double[4];
a[0]=1;
a[1]=2;
a[2]=3;
a[3]=4;
cout <<"size of double:"<<sizeof(double)<<endl;
a[100]=100; // why is it not crashing here?
return 0;
}
Could someone explain me whats happening here? Shouldn't this crash at a[100]=100?
Why doesn't the below program crash?
From perspective of C++: Because the behaviour of the program is undefined. The program is neither guaranteed to crash nor to not crash. Nor are there any other guarantees about the behaviour.
From perspective of the operating system: Assuming the compiler did not remove the access due to having detected undefined behaviour, it probably didn't crash because that memory happened to be mapped for the process. In general, it is not safe to assume that all buffer overflows could be detected.
This question already has answers here:
What is the purpose of allocating a specific amount of memory for arrays in C++?
(5 answers)
Closed 5 years ago.
#include<iostream>
using namespace std;
int main()
{
char a[]="robert";
cin>>a;
cout<<a;
}
So size of a is now fixed as 7 bits as intuitive. Now if I read something as "qwertyuiop" into 'a' which is larger than 7 bits, it is expected to show overflow. However nothing such happens and it prints the output normally. What's going on here?
Writing out of the bounds is an undefined behaviour.
In this case looks ok, but what happens if...
#include<iostream>
using namespace std;
int main()
{
char a[5];
char b[7];
cin >> a;
cin >> b;
cout << a << endl;
}
Input:
kingkong
monkeyhunter
Output:
kingkmonkeyhunter
They are mixed up!
You should be careful with arrays in C++, it could be no visible effects if you try to write out of bounds.
The operating system (with the help of the processor) defines a region of memory to which your application is allowed to read/write. When you read outside what you are expected, the processor triggers a hardware exception which is caught by your operating system and this triggers the termination of you application.
However, reading outside an array does not necessarily read outside the boundary of your application (you could for example write/read to another variable of your own code). As an example, at the end of your memory region, you usually have the program stack in reverse order.
C++ specifies the reading/writing outside the range of your array as undefined behavior. In this case, it may crash or not in a 'random-like' fashion.
This question already has answers here:
Stack overflow visual C++, potentially array size?
(2 answers)
Closed 9 years ago.
Why is this code giving segmentation fault? I am using code::blocks.
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int a[555555];
}
This is what called stack overflow.
Generally stack size are small and you can't allocate memory in such a large amount on stack.
For this purpose programmers allocate it on heap (using dynamic allocation). In C, you can use malloc family function
int *a = malloc(sizeof(int)*55555); // Use free(a) to deallocate
In C++ you can use new operator
int *b = new int[555555]; // Use delete [] to deallocate
Because you are trying to allocate a bit over 2MB (Previously I failed at math and thought it was 2GB) of memory on stack, which then blows the stack.
Note: for windows the default stack size for a particular thread is 1MB and on Gnu/linux you can find out stack size value using ulimit -s command.
You've come to the right place to ask the question. ;)
The array is large and lives on the stack. The code crashes because it runs out of the limited stack space.
If you allocate a on the heap, the problem will likely disappear.
As other already had told you you are trying to allocate a large amount of memory in the stack which space is usually very limited.
See for instance:
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int a[555555];
int* b = new int[555555];
delete [] b;
}
In that snipped, you have two arrays of integers, one allocated in the heap and the other allocated on the stack.
Here you can find some explanations about which are the differences between the heap and the stack:
What and where are the stack and heap?
http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html
I've got some considerations on your code.
First, modern compilers will recognize that a is unused and then it'll be thrown away.
But if you put a certain value into a certain position, a will be allocated, even though it's bigger than the stack size. The kernel will not allow you do that: that's why you get a SIGSEGV.
Finally, you should rely on either std::array or std::vector rather than pure C arrays.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Segmentation fault on large array sizes
A segmentation fault occurs when I run the program.
#include<iostream>
using namespace std;
int main(){
int x[2000][2000];
int y;
cin >> y;
}
However, the following two programs are OK, when I run them.
#include<iostream>
using namespace std;
int x[2000][2000];
int main(){
int y;
cin >> y;
}
and
#include<iostream>
using namespace std;
int main(){
int x[2000][2000];
int y;
}
I am quite confused. Can anyone tell me why?
Congratulations, you've found a stack overflow.
In the first example, the large array x pushes y past the end of the stack, so accessing it crashes the program. (2) doesn't crash because the large array you declared is in the data segment and so not on the stack; (3) doesn't crash because you're not actually accessing memory past the end of the stack (you've declared it, but aren't reading or writing it).
In your first example, you are attempting to allocate 20,000*20,000*4 bytes (assuming 32-bit integers) on the stack. This amount to about 16MB of data, which is more than the stack size allocated for you by the compiler (typically about 1MB), so you run out of (stack) memory
In the second example, the compiler allocates the memory for x in a separate global space (not on the stack), which has enough space to hold it.
The third example is trickier, because it should seemingly result in the same situation as the first, but it is possible that your compiler optimized out the function as it deemed that no meaningful work is being done in that function (so no memory allocation for the local variables)