-4

Can anyone please tell what is the issue in code? It gives me correct output but at the end i ma getting error " Below code gives me error * stack smashing detected *:"4

I used GDB to check I get signal at the end as

__stack_chk_fail () at stack_chk_fail.c:28 28 stack_chk_fail.c: No such file or directory.

#include <iostream>
#include <string.h>
#include <iomanip>

using namespace std;

void computeLps (char p[], int n) {
    int *lps = new int[n];
    int len = 0;
    lps[0] = 0;
    int i = 1;
    while(i < n)
    {
        /* code */
        if(p[len] == p[i]){
            len ++;
            lps[i] = len;
            i++;
        }
        else {
            if(len != 0) {
                len = lps[len - 1];
            }
            else{
                lps[i] = 0;
                i++;
            }
        }
    }

    for (int i = 0; i < n; ++i)
    {
        /* code */
        cout << lps[i]<<" ";
    } 
    cout <<endl;
}

int main() {

    char b[] = "ABABDABACDABABCABAB";
    char a[] = "ABABCABAB";

    strcat (b,"$"); 
    strcat (b,a);

    //cout << b;

    computeLps(b,strlen(b));
    return 0;
}

1 Answers1

0

Because you used an array of characters for b, the memory allocated to your array b on the stack is fixed. If you want to avoid this, make the char array large enough to be added to or try using std::string and concatenate with the tips in this link. How to concatenate two strings in C++?

std::string will dynamically allocate memory and grow when it needs to if the memory allocated for it is all used.

9Breaker
  • 724
  • 6
  • 16