程序给出SIGSIGV错误

Program giving SIGSIGV Error

本文关键字:错误 SIGSIGV 程序      更新时间:2023-10-16

我写了下面的c++程序,它给了我

SIGSIGV输入太大错误。

基本上,下面的程序输出比数组中当前数字小的数字。我使用BST和数组来实现。

#include <iostream>
using namespace std;
struct bst {
    long long int data;
    struct bst *right;
    struct bst *left;
};
struct bst *head=NULL;
//function to increment 
void increment(struct bst *node,long long int w[]) {
    if(node==NULL)
    return;
    w[node->data] += 1;
    increment(node->left,w);
    increment(node->right,w);
}
void insert(long long int data,long long int w[]){
    struct bst *node;
    struct bst *current;
    current=head;
    if(head==NULL) {
        node = new bst;
        node->data = data;
        node->right = NULL;
        node->left=NULL;
        head=node;
        }else {
        while(1) {
            if(data > current->data){
                if(current->right!=NULL)
                current=current->right;
                else {
                    node = new bst;
                    node->data = data;
                    node->right = NULL;
                    node->left=NULL;
                    current->right=node;
                    break;
                }
            }
            else{
                if(current->left!=NULL){
                    //if data is less than current number than incremet 1 in right sub tree of current node 
                    //and current node
                    w[current->data] +=1;
                    increment(current->right,w);
                    current=current->left;
                }
                else {
                    node = new bst;
                    node->data = data;
                    node->right = NULL;
                    node->left=NULL;
                    current->left=node;
                    //if data is less than current number than incremet 1 in right sub tree of current node 
                    //and current node
                    w[current->data] +=1;
                    increment(current->right,w);
                    break;
                }
            }
        }
    }
}
void deletenode(struct bst *node) {
    if(node == NULL)
    return;
    deletenode(node->left);
    deletenode(node->right);
    delete(node);
}

int main() {
    int t;
    cin>>t;
    while(t--) {
        long long int n;long long int counter=0;
        cin>>n;
        long long int a[n];
        //array to keep count of numbers which are less than index of w[i]
        long long int w[1000000]={0};
        for(long long int i=0;i<n;i++) {
            cin>>a[i];
            insert(a[i],w);
        }
        for(long long int i=0;i<n;i++) {
            cout<<w[a[i]]<<" ";
        }
        cout<<"n";
        //deleting BST
        deletenode(head);
        head=NULL;
    }
    return 0;
}

感谢您的帮助。

main中这可能会导致问题-

long long int w[1000000]={0};

应该在堆上分配内存。你可以这样做-

long long int *w=new long long int[1000000]