简体   繁体   中英

"Program received signal SIGSEGV , Segmentation fault” When trying to get all keywords of 3-character combinations using recursion

I am trying to get all keywords of 3 characters using recursion but after some calls maybe call stack is full and the program crash with segmentation fault error , Code :

#include <cs50.h>
#include <stdio.h>

void three_Characters(char c, char c2, char c3);

int main(void){
    three_Characters('A', 'A', 'A');
    return 0;
}

void three_Characters(char c, char c2, char c3){

//print 3-characters 
    printf("%c%c%c - ", c, c2, c3);

    /*Recursion termination*/
    if(c == 'z' && c2 == 'z' && c3 == 'z'){
        return;
    }

    /*Avoid symbol characters */
    if(c3 == 'Z'){
        c3 += 6;
        if(c2 == 'Z'){
            c2 += 7;
            if(c == 'Z'){
            c += 7;
            }
        }
    }

    if(c3 == 'z'){
        if(c2 == 'z'){
            c += 1;   c2 = 65;   c3 = 64;
        }else{
            c2 += 1;  c3 = 64;
        }
    }
    three_Characters(c, c2, c3 + 1); 
}

How deep do you expect your recursion to run?

You will get 52 levels iterating the last character from 'A... Za...z', 52*52 levels iterating over the last two characters, and 52*52*52 total recursion depth.

That's a recursion that is 140608 levels deep.

Every time you call a routine, you use some amount of stack. A return address must be saved. Often some registers must be saved as well.

On a 64-bit system, without optimization, it is likely that at least 32 bytes of stack will be used for each recursion level. That's 4499456 bytes. The stack limit on Linux is often 8MB, so you shouldn't run out of stack (and your program does not crash for me in either 64 or 32-bit mode). But you'll be using more than half of your available stack.

Your system probably has a lower stack limit (perhaps 4MB). If so, your program will run out of stack.

On Linux (and other UNIX OSes), use ulimit -s to find out what your current stack limit is, and ulimit -s unlimited to remove the stack limit (this should also allow your program to run to completion without hitting SIGSEGV ).

PS Using recursion for this trivially iterable problem is ill -advised, precisely because you will use a lot of stack space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM