【问题标题】:My program crashes if the vector is too large?如果向量太大,我的程序会崩溃?
【发布时间】:2019-09-12 07:35:16
【问题描述】:

当我用大于 12 个元素的大型向量测试我的程序时,它会崩溃(我收到 lldb 错误)。但是,它适用于小向量。我认为它正在尝试访问它不应该访问的内存空间,但我不知道如何修复它。 该程序应该打印出元素总和等于“目标”的向量 另外,有没有不同的表达方式: if (i & (1

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int c = 0;
/* find subsets of a given set */
void findSubsets(int *value, int n, int i) {
    int j;
    if (i < 0)
        return;

    for (j = 0; j < n; j++) {
        /*
         * checking jth bit is set in i.  If
         * it is set, then fetch the element at
         * jth index in value array
         */
            if (i & (1 << j)) {
                suma = suma + value[j];
        }

    /* recursive call */
    findSubsets(value, n, i - 1);
    return;
}

int main() {

    /* 2^n - indicates the possible no of subsets */
    int count = pow(2, size);

    /* finds the subsets of the given set */
    findSubsets(vector, size, count - 1);

    return 0;
}

我希望能够将此程序用于大型向量(最多约 20 个)

【问题讨论】:

    标签: c debugging crash


    【解决方案1】:

    问题是你得到了52428810 递归函数调用。这将导致堆栈溢出。尝试迭代而不是递归:

    for (int i = 0; i < count; i++) {
        findSubsets(vector, size, i);
    }
    

    并删除findSubsets内的递归调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      相关资源
      最近更新 更多