简体   繁体   English

C确定堆栈溢出

[英]C identified STACK OVERFLOW

I've made the code above and I've used 2 different compilers, one says "Segmentation Fault" and the other one says "handle_exceptions: Exception: STATUS_STACK_OVERFLOW". 我已经完成了上面的代码,并使用了2种不同的编译器,其中一个说“ Segmentation Fault”,另一个说“ handle_exceptions:Exception:STATUS_STACK_OVERFLOW”。 Here is the code. 这是代码。

int main() {
    int k, x, f, i, j, tmp, ct;
    scanf("%d %d", &k, &x);
    int w[k];
    for( f = 0; f<k; f++){
        scanf(" %d", &w[f]);
    }
    while(x--){
        scanf("%d %d", &i, &j);
        tmp = 3;
        for(ct = j; i<=ct<=j; ct--){
            if(tmp > w[ct]){
                tmp = w[ct];
            }
        }
        printf("%d\n", tmp);
    }
    return 0;
}

I've commented this code, line by line, and testing and I've the error here: 我已经逐行注释了此代码,并进行了测试,但这里出现了错误:

int w[k];

I don't know what I can do, because the k variable is already defined when the declaration of this vector happens. 我不知道该怎么办,因为在声明此向量时已经定义了k变量。 Can somebody help me? 有人可以帮我吗?

If you defined an array like this: 如果您定义这样的数组:

int w[k];

It will be stored in the stack, which has a limited size. 它将存储在大小有限的堆栈中。

If you initialize with malloc the data will be store in the heap (which also has a limited size, but it will allow you to store more data) 如果使用malloc初始化,则数据将存储在堆中(堆的大小也有限,但是可以存储更多数据)

int *w = malloc(sizeof(int) * k);

Have you tried this? 你有尝试过吗?

Check this for a difference between stack vs heap. 检查此内容以了解堆栈与堆之间的差异。

Always checked the returned value from malloc() , this is just an example, but it is a bad practice to not the returned value of malloc() . 始终检查malloc()的返回值,这只是一个示例,但是不使用malloc()返回值是一种不好的做法。

You cannot define a variable size during run-time unless you use dynamic memory allocation. 除非使用动态内存分配,否则无法在运行时定义变量大小。

As I can see, you are trying to set the variable size based on the user's input. 如我所见,您正在尝试根据用户输入来设置变量大小。

To do this, you must use dynamic memory allocation. 为此,您必须使用动态内存分配。

scanf("%d %d", &k, &x);
if(k > MAX_SIZE) {
    return -1;
}
int *w = malloc(sizeof(int) * k);

Now you have a memory allocated based on the size entered by user's input. 现在,您已经根据用户输入的大小分配了内存。 But make sure that you are imposing some limits, because the heap memory is limited. 但是请确保施加一些限制,因为堆内存是有限的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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