Search code examples
c++csegmentation-faultackermann

How to run Ackermann's Fuction without error in C/C++?


So how to I run Ackermann's Function without running into Segmentation fault (core dumped) error because of my program tries to access/expand memory that it doesn't hace access to? Maybe expanding the memory limit of GCC to 256MB? It causes this error at about 9MB of memory usage. I run Manjaro Linux

Code:

#include<stdio.h>

int ack (int m, int n) {

    if (m == 0)
        return n + 1;
    else if (n == 0)
        return ack(m - 1, 1);
    else
        return ack(m - 1, ack(m, n - 1));
}

int main() {

    int i, j;

    for (i = 0; i <= 5; i++)
        for (j = 0; j <=5; j++)
            printf("Result for ackermann(%d, %d) is: %d\n",i, j, ack(i, j));

    return 0;
}

Code added for reproducing results


Solution

  • This is almost certainly not a "too much memory used" problem. Note that GCC doesn't have a memory limit. If you have a real limit, it's a function of your operating system. Under Mac OS or one of the UNIX variants, see the ulimit command. I have no idea what you do under Windows.

    If you're getting a segmentation fault, it's because you're attempting to access memory you haven't allocated. This is most likely due to one of these three conditions:

    • Dereferencing a null pointer
    • Dereferencing an entirely-uninitialized pointer
    • Dereferencing a pointer stored in memory that has been reused (which can point to who knows where)

    Your core file should tell you what line of code is causing the seg fault. And THAT should help you trace why it's happening.