C ++断言语句导致段错误

时间:2016-02-11 02:21:46

标签: c++ assert

我试图理解仿函数。我有以下程序,我是从functors and their uses借用和修改的。

#include <iostream>                                                                                                                                                                                                                          
#include <vector>
#include <assert.h>
#include <algorithm>

/*
 * A functor is pretty much just a class which defines the operator(). 
 * That lets you create objects which "look like" a function
 **/
struct add_x
{
    add_x(int y) : x(y) 
    {   

    }   
    int operator()(int y) const {
        return x + y;
    }   

private:
    int x;
};

int main()
{
    /* create an instance of the functor class*/
    add_x add42(42);
    /* and "call" it */
    int i = add42(8); 
    /*and it added 42 to its argument*/
    assert(i == 50); 

    /*assume this contains a bunch of values*/
    std::vector<int> in; 
    std::vector<int> out(in.size());
    /*  
     * Pass a functor to std::transform, which calls the functor on every element
     * in the input sequence, and stores the result to the output sequence
     */
    std::transform(in.begin(), in.end(), out.begin(), add_x(1));
    /*for all i*/
    assert(out[i] == (in[i] + 1)); 
    return 0;
}

我在main()中的第二个assert语句中遇到了分段错误。 (assert(out[i] == (in[i] + 1));)我似乎无法弄明白为什么?

1 个答案:

答案 0 :(得分:4)

in.size()将返回0,因为您还没有添加任何内容。这意味着out被初始化为空向量。

out[i]将尝试访问向量的第51个元素(因为STL索引从零开始),这是不存在的,因此是段错误。

评论/*assume this contains a bunch of values*/无效,因为您的代码未显示in包含任何内容。

使用vector(size_t n, const value_type& val)构造函数重载为向量提供初始值以修复此错误:

using namespace std;

...

vector<int> in(51, 0); // initializes the vector with 51 values of zero
vector<int> out( in.size() ); // 51
...

assert( out[i] == int[i] + 1 );