Open In App

Memory Limit Exceeded Error

Last Updated : 13 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Memory Limit Exceeded Error: It typically occurs when no memory limit has been set. It means that the program is trying to allocate more memory than the memory limit for the particular problem. For Example, if the memory limit is 256 MB, then there is no need to write code that requires more than 256 MB of memory. Generally, all online platforms have the same memory limit as 256 MB. There might be many more reasons due to which this error can occur.

Program 1:

Below is the C++ program to declaring a global 1D array of size 107:

C++




// C++ program to declare the array
// of size 10^7 globally
 
#include <bits/stdc++.h>
using namespace std;
 
// Variable N initialized
const int N = 1e7;
 
// Global array is declared
int a[N];
 
// Driver Code
int main()
{
    for (int i = 0; i < N; ++i) {
        a[i] = i;
    }
    cout << a[N - 1];
 
    return 0;
}


Output: 

9999999

 

Explanation: This code will successfully compile and output is 9999999 because the 1-D array has been declared globally of size 107.

Program 2: Below is the C++ program to declare a global 1D array of size 108:

C++




// C++ code declaring a global 1-D
// array of size 10^8
#include <bits/stdc++.h>
using namespace std;
 
// Variable N is initialized
const int N = 1e8;
 
// Global array is declared
int a[N];
 
// Driver Code
int main()
{
    for (int i = 0; i < N; ++i) {
        a[i] = i;
    }
    cout << a[N - 1];
    return 0;
}


 

 

Output:

 

Memory Limit Exceeded

 

or

 

Segmentation Fault (SIGSEGV)

 

Explanation: In the above program, the users will get a memory limit and exceed as an error, but some online platforms can also give an error as a Segmentation Fault(SIGSEGV). This is because users can only declare a global 1-D array of size 107, not more than that. Here, one declared a global 1-D array of size 108 and therefore has an error as the memory limit exceeded (MLE) occurs.

 

Note: 

 

  • Note that trying to exceed the memory limit may sometimes result in other errors.
  • An example would be if users are using malloc in C to allocate memory. If malloc fails because the user is trying to allocate too much, it simply returns a null pointer which, unless checked for it, would probably cause a Run Time Error when the user tries to use it.
  • Similarly, trying to allocate too much memory in C++ using new would cause a SIGABRT and give Run Time Error.

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads