Skip to content
Related Articles

Related Articles

Improve Article

Memory Limit Exceeded Error

  • Difficulty Level : Easy
  • Last Updated : 13 Jul, 2021

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.

 

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :