segmentation fault on some linux machines
Feb 25, 2010 at 2:30pm UTC
I have written the following code which gives a segmentation fault on the line
delete [] string1;
This behavior is seen only on a few linux machines and I would like to know the reason behind this
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
#include<iostream>
using namespace std;
#include<string.h>
int main(int argc, char * argv[])
{
char * string1 = new char [5800];
char * str1 = "Peer =Peer" ;
char * str2 = ": Realm=mnc301.mcc302.3gppnetwork.org " ;
char num[3]={'0' ,'0' ,'\0' };
num[3]='\0' ;
const char * sPtr =const_cast <char *>(&num[0]);
for (int i =1; i<63; i++)
{
char * tempString = new char [strlen(str1)+strlen(str2)+(i/10+1)];
strcpy(tempString,str1);
num[0]='0' +(i/10);
num[1]='0' +(i%10);
strcat(tempString, sPtr);
strcat(tempString, str2);
if (i==1)
strcpy(string1, tempString);
else
strcat(string1, tempString);
cout<<"tempString=" <<tempString<<endl;
delete [] tempString;
}
cout<<"string=" << string1<<endl;
cout<<"strlen of string=" <<strlen(string1)<<endl;
delete [] string1;
return 0;
}
Thanks,
Krishna
Feb 25, 2010 at 2:51pm UTC
Because you have multiple buffer overruns of tempString. The math for computing its size makes no sense. Why on Earth would you do this rather than use std::string?
Feb 25, 2010 at 2:55pm UTC
Line 10 is overflowing the 'num' array.
tempString doesn't reserve space for the terminator character under all circumstances.
Not a bug, but line 9 could be rewritten as char num[]="00" ;
.
Topic archived. No new replies allowed.