Program crashes for generated string

Here I am trying to implement longest common sub-sequence algorithm for two randomly generated strings. This program gives me expected output for two given strings. But when I try to run this for generated string, the .exe file crashes. Help me please.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

string generateString(int);
void LCS_Length(string &X, string &Y, int, int);
void Print_LCS(string b[10][10], string& X, int, int);

int c[10][10];
string b[10][10];

int main()
{
    srand(time(0));
    string X, Y;
    X = generateString(10);
    Y = generateString(10);
    LCS_Length(X, Y, X.size(), Y.size());
    cout << c[X.size()][Y.size()] << endl;
    Print_LCS(b, X, X.size(), Y.size());
    cout << endl;
    return 0;
}

string generateString(int length)
{
    static const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int strLen = sizeof(alphabet)-1;
    char genRandom;
    string str;
    for(int i=0; i<length; i++){
        genRandom = alphabet[rand()%strLen];
        str += genRandom;}
    return str;}

void LCS_Length(string &X, string &Y, int m, int n){
    for(int i=0; i<=m; i++)	{c[i][0] = 0;}
    for(int j=0; j<=n; j++)	{c[0][j] = 0;}
    for(int i=1; i<=m; i++){
        for(int j=1; j<=n; j++){
            if(X[i-1] == Y[j-1]){
                c[i][j] = c[i-1][j-1]+1;
                b[i][j] = "Upper Left Corner";}
            else if(c[i-1][j] >= c[i][j-1]){
                c[i][j] = c[i-1][j];
                b[i][j] = "Up";}
            else{
                c[i][j] = c[i][j-1];
                b[i][j] = "Left";} } } }

void Print_LCS(string b[10][10], string &X, int i, int j){
    if(i==0 || j==0) return;
    if(b[i][j] == "Upper Left Corner"){
        Print_LCS(b, X, i-1, j-1);
        cout << X[i-1];}
    else if(b[i][j] == "Up"){
        Print_LCS(b, X, i-1, j);}
    else{
        Print_LCS(b, X, i, j-1);}}
Last edited on
HEre is your problem:
1
2
3
4
5
int c[10][10];
string b[10][10]
//...
for(int i=1; i<=m; i++){
        for(int j=1;[code] j<=n
; j++){
if(X[i-1] == Y[j-1]){
c[i][j] = c[i-1][j-1]+1;
b[i][j] = "Upper Left Corner";}[/code]Last valid index for c and b is [9][9].
In your function both m and n are 10, which means that eventually your code will try to access value [10][0], and late even [10][10]. Which will lead to out of bound access and in case of string array almost definitive crash.
I just sort it out & almost delete the question
Thanks anyway :)
almost delete the question

Don't do that. It makes the thread useless for anyone else trying to use this forum as a learning resource.
okay :)
Topic archived. No new replies allowed.