Why does this code not cause a SIGSEGV?

Why does this code not cause a segmentation fault when it is supplied with input 1 1000?

#include <iostream>
#define MAX 1000
 
using namespace std;
 
long long dp[MAX] = {-1};
long long func(int n)
{
	if(dp[n] > 0)
	{
		return dp[n];
	}
	else {
		return dp[n] = (n * n) + func(n - 2);
	}
}
int main()
{
	dp[0] = 0;
	dp[1] = 1;
	dp[2] = 4;
	int T;
	cin >> T;
	while (T--)
	{
		int n;
		cin >> n;
		cout << func(n) << endl;
	}
	return 0;
}

SIGSEGV error is caused when you try to access the memory address which is not assigned in the system or you are not allowed to access it.
Here, when you give n = 1000 , you are trying to access &dp[999]+sizeof(data type) which may be the next address in the contiguous block. So it will return some garbage value because memory is there and is accessible.
But if you try to give greater values of n you may get SIGSEGV error.

1 Like