Jun 20, 2019 at 4:27pm UTC
Hi folks,
Can someone help with below code giving core dump on delete statement in destructor.
CODE:
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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
#include <iostream>
using namespace std;
class my_str{
int l1, l2;
char * arr1;
int * arr2;
public :
my_str(){//default ctr
l1 = 0; l2 = 0;
arr1 = new char [10];
arr2 = new int [3];
}
my_str(const my_str & tmp){//copy ctr
l1 = tmp.l1;
l2 = tmp.l2;
arr1 = new char [l1];
arr2 = new int [l2];
for (int i=0; i<l1; i++){
arr1[i] = tmp.arr1[i];
}
for (int i=0; i<l2; i++){
arr2[i] = tmp.arr2[i];
}
}
int count_vowels(char * tmp){
int count=0;
for (int i = 0; tmp[i]!='\0' ; i++){
if (tmp[i]=='a' ||tmp[i]=='e' ||tmp[i]=='i' ||tmp[i]=='o' ||tmp[i]=='u' )
{
count++;
}
}
return count;
}
void push_str(char * inp){
int count = count_vowels(inp);
for (int i=0; i<l2; i++){
if (arr2[i] == count){
cout<<"\nCannot insert. Need Unique Vowels" ;
return ;
}
}
int tmp_len = l1;
int i;
for (i=0; inp[i] != '\0' ; i++)
{
arr1[tmp_len] = inp[i];
tmp_len++;
}
l1 = l1+i;
arr2[l2] = count;
l2++;
return ;
}
void print_str()
{
cout<<"l1 : " <<l1<<"\nString is : " ;
for (int i=0; i<l1; i++){
cout<<arr1[i];
}
cout<<endl;
cout<<"l2 : " <<l2<<"\nVowel Count array : " ;
for (int i=0; i<l2; i++){
cout<<arr2[i]<<" " ;
}
}
~my_str(){//dtr
cout<<"\nInside dtr" <<endl;
fflush(stdout);
delete []arr2;//this line is causing core dump
delete []arr1;
arr1=NULL;
arr2=NULL;
cout<<"exiting dtr" ;
fflush(stdout);
}
};
//In a custom string object, only strings with unique num of vowels must be allowed to be inserted.
int main()
{
my_str S1;
S1.push_str("trees" );
S1.push_str("animals" );
S1.push_str("mesopotemia" );
cout<<"\nPrinting S1" <<endl;
S1.print_str();
my_str S2 = S1;
S2.push_str("egypt" );
S2.push_str("jaguar" );
cout<<"\nPrinting S2 : " <<endl;
S2.print_str();
return 0;
}
OUTPUT :
Printing S1
l1 : 23
String is : treesanimalsmesopotemia
l2 : 3
Vowel Count array : 2 3 6
Cannot insert. Need Unique Vowels
Printing S2 :
l1 : 28
String is : treesanimalsmesopotemiaegypt
l2 : 4
Vowel Count array : 2 3 6 1
Inside dtr
*** Error in `./a.out': munmap_chunk(): invalid pointer: 0x0000000000715c80 ***
Aborted (core dumped)
Last edited on Jun 22, 2019 at 5:25am UTC
Jun 20, 2019 at 6:54pm UTC
I don't see where l2 is set to a useful value.
arr2 = new int[l2];
Last edited on Jun 20, 2019 at 6:55pm UTC
Jun 21, 2019 at 3:41pm UTC
arr{1,2} are terrible names.
well, if he had worked a yohoho in there too, maybe...