我正在Windows 7上使用MinGW使用Code :: Blocks;
我有这个功能,可以正常工作:
Hueso* getSkel(int cual)
{
unsigned int cont; //SkelCargados and CantSkel are global vectors
for (cont =0; cont < SkelCargados.size();cont++) if ( CantSkel[cont] == cual) break; // EDIT: I changed <= with < before SkelCargados.size()
if (SkelCargados.empty() || cont>SkelCargados.size())
{
char linea[LINEA]; //LINEA is a macro. Max value for this string.
FILE * f = fopen("esqueletos.txt","rt");
if (f == NULL) return NULL;
fgets (linea,LINEA,f);
vector<float> puntos_; // <-- please pay attention in these 4 lines
puntos_.push_back(2.2);
puntos_.push_back(2.2);
puntos_.push_back(2.2);
while (!feof(f))
{
//...
}
fclose(f);
}
return SkelCargados[CantSkel[cont]];
}
而这个,在尝试第二个push_back时崩溃。 (NOT)有趣的是,当我将向量及其push_back()放在fgets之前时,它的行为正常。
编辑:如果我将向量声明为全局变量,它也可以正常工作。
bool CargarMapa()
{
char linea[LINEA];
FILE * f = fopen("mapas.txt","rt");
if (f == NULL) return false;
fgets (linea,LINEA,f);
vector<float> puntos_;
puntos_.push_back(2.2);
puntos_.push_back(3); //Here it crashes
puntos_.push_back(4.2);
while (!feof(f))
{
//...
}
fclose(f);
return true;
}
这是崩溃时发生的情况:调试器抛出“程序接收到的信号SIGSEGV,分段错误”。并转到文件“ new_allocator.h”中标有“ HERE IT STOPS”注释的行:
//(I did not write the following comment)
/*
@brief An allocator that uses global new, as per [20.4].
@ingroup allocators
This is precisely the allocator defined in the C++ Standard.
- all allocation calls operator new
- all deallocation calls operator delete
*/
template<typename _Tp>
class new_allocator
{
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef _Tp* pointer;
typedef const _Tp* const_pointer;
typedef _Tp& reference;
typedef const _Tp& const_reference;
typedef _Tp value_type;
template<typename _Tp1>
struct rebind
{ typedef new_allocator<_Tp1> other; };
new_allocator() throw() { }
new_allocator(const new_allocator&) throw() { }
template<typename _Tp1>
new_allocator(const new_allocator<_Tp1>&) throw() { }
~new_allocator() throw() { }
pointer
address(reference __x) const { return std::__addressof(__x); }
const_pointer
address(const_reference __x) const { return std::__addressof(__x); }
// NB: __n is permitted to be 0. The C++ standard says nothing
// about what the return value is when __n == 0.
pointer
allocate(size_type __n, const void* = 0)
{
if (__n > this->max_size())
std::__throw_bad_alloc();
return static_cast<_Tp*>(::operator new(__n * sizeof(_Tp))); //HERE IT STOPS
}
请帮我。 :(
最佳答案
for (cont =0; cont<=SkelCargados.size();cont++) if ( CantSkel[cont] == cual) break;
不是你想要的。您可能想在循环终止条件中使用比较运算符
<
而不是<=
。如所写,如果该向量中只有一项,则可能会以break
的索引结尾1
,这将导致您尝试索引到仅具有一个位置的向量中的1
位置。 (请记住,向量,数组和其他类似的构造都是零索引的,因此[0]
是第一个元素,[1]
是第二个元素,依此类推)该错误很可能不是在
push_back
实际对您失败的地方,而是在代码中破坏内存的其他地方(这导致未定义的行为)。关于c++ - C++- vector push_back()在fgets()之后不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13190175/