Function using dynamic mem. allocation - getting seg. fault
Nov 24, 2014 at 4:13am UTC
Hi all,
I pretty much just want the nonzeroCopy function to return a pointer to an array of something, except without all the zero's. This is, of course, done with dynamic memory allocation. I'm getting a seg. fault here, and I'm not sure why.
Would really appreciate the guidance here.
Thanks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
#include <iostream>
#include <cstdlib>
using namespace std;
int * nonzeroCopy( unsigned & nonzeroEls, const int a[], unsigned els );
void show( const int a[], unsigned elements );
void die(const string & msg);
int main(){
unsigned nonZeroElsIn;
int arr2[4] = {4, 0, 0, -6};
int * newArr2 = nonzeroCopy(nonZeroElsIn, arr2, 4);
show(newArr2, nonZeroElsIn);
}
int * nonzeroCopy( unsigned & nonzeroEls, const int a[], unsigned els )
{
for (int i = 0; i < els; i++)
{
if (a[i] != 0)
nonzeroEls++;
}
int * newNonZeroArr;
try
{
newNonZeroArr = new int [nonzeroEls];
for (int i = 0; i < nonzeroEls; i++)
{
if (a[i] != 0)
newNonZeroArr[i] = a[i];
}
}
catch (const bad_alloc &)
{
die("nonZeroCopy: Alloc Failure" );
}
return newNonZeroArr;
}
void show( const int a[], unsigned elements )
{
for (int i = 0; i < elements; i++)
cout << a[i] << endl;
}
void die(const string & msg)
{
cerr << "Fatal error: " << msg << endl;
exit(EXIT_FAILURE);
}
Nov 24, 2014 at 7:52am UTC
What is the value of nonZeroElsIn just before you call nonzeroCopy()?
How will nonzeroCopy() change that value?
Line 38. Your sample data performs these:
1 2
newNonZeroArr[0] = 4;
newNonZeroArr[3] = -6;
The latter reveals the error in logic, doesn't it?
Topic archived. No new replies allowed.