1

I am running this c++ program which is continuously giving me sysmalloc assertion failed error. I am using g++-4.8.

# 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

The error is when at the last line I allocate the vector result. How do I avoid this error?

sudeepdino008
  • 3,194
  • 5
  • 39
  • 73
  • What I don't get is why you didn't use vector in your compositeSignal code instead of using "new" (which was used incorrectly anyway, as pointed out in the answer). In addition, "typedef struct" is not necessary in a C++ struct definition. – PaulMcKenzie Jan 30 '14 at 22:12
  • See my answer [here](https://stackoverflow.com/questions/31936229/c-sysmalloc-assertion-failure/46511080#46511080), the exact same thing happened to me. – forumulator Oct 01 '17 at 09:41

1 Answers1

2

You have undefined behaviour because you are only allocating a single int for each of frequency and amplitude and then you're trying to access amplitude[1] and so on. The new int(n) syntax will allocate a single int and initialise it with value n. What you're looking for is new int[n], which will allocate an array of n ints.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324