2014-01-30 73 views
1

我正在運行這個C++程序,它不斷給我sysmalloc assertion失敗的錯誤。我正在使用g ++ - 4.8。sysmalloc聲明失敗使用矢量

# include <iostream> 
# include <complex> 
# include <vector> 
# include <stdlib.h> 
# include <time.h> 
# include <climits> 
# include <cstdio> 
#define getRand(x,y) (rand()%((y)-(x)+1)+(x)) 
using namespace std; 


typedef complex<double> Complex; 

typedef struct compositeSignal{ 
    int *frequency; 
    int *amplitude; 
    int num; 

    compositeSignal(int n) 
     { 
      frequency = new int(n); 
      amplitude = new int(n); 
      num = n; 

      for(int i=0;i<num;i++) 
      { 
       amplitude[i] = getRand(1,100); 
       cout<<amplitude[i]<<" "; 
       frequency[i] = getRand(100,600); 
       cout<<frequency[i]<<endl; 
      } 

     } 


    double getVal(double t) 
     { 
      double val = 0; 
      for(int i = 0;i<num;i++) 
       val += amplitude[i]*sin(2*3.142*frequency[i]*t); 
      return val; 
     } 
}compositeSignal; 


int main() 
{ 
    srand(time(NULL)); 
    int numOfSig = 5; 
    compositeSignal sig1(numOfSig);// sig2(numOfSig); //define and initialize 2 composite signals 


    vector<int> result(10); 

} 

ERROR:

a.out: malloc.c:2369: sysmalloc: Assertion `(old_top == (((mbinp 
tr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offseto 
f (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned l 
ong) (old_size) >= (unsigned long)((((__builtin_offsetof (struct 
malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((
2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((uns 
igned long)old_end & pagemask) == 0)' failed.     
Aborted 

當在最後一行我分配矢量result的錯誤是。我如何避免這個錯誤?

+0

我沒有得到的是爲什麼你沒有在你的compositeSignal代碼中使用vector而不是使用「new」(正如答案中指出的那樣,它被錯誤地使用了)。另外,在C++結構定義中「typedef struct」不是必需的。 – PaulMcKenzie

+0

看到我的回答[這裏](https://stackoverflow.com/questions/31936229/c-sysmalloc-assertion-failure/46511080#46511080),同樣的事情發生在我身上。 – forumulator

回答

2

你有不確定的行爲,因爲你只分配爲每frequencyamplitudeint,然後你想訪問amplitude[1]等。 new int(n)語法將分配單個int並使用值n初始化它。您正在尋找的是new int[n],它將分配陣列nint s。

+0

糟糕!這很尷尬。 – sudeepdino008