<da************@gmail.comwrote in message
news:11*********************@m7g2000cwm.googlegrou ps.com...
Hello!!
I'm studying c++ and I'm trying to get a little piece of code working,
but I'm getting a segfault with strlen here:
void tabhash::set (url *U) {
uint hash = U->hashCode();
char* url = U->giveUrl();
char* chash = (char*)hash;
char* Insert1="INSERT INTO sep_hashtable VALUES (";
char* Insert2=",0,'";
char* Insert3="');";
char* Insert=new
char[strlen(Insert1)+strlen(chash)+strlen(Insert2)+strl en(url)+strlen(Insert3)];
strcpy( Insert, Insert1);
strcat( Insert, chash);
strcat( Insert, Insert2);
strcat( Insert, url);
strcat( Insert, Insert3);
if (mysql_query(&mysql,Insert)) {
cerr << "Cannot insert into sep_hashtable : "
<< strerror(errno) << endl;
exit(1);
}
}
I can't find out why I'm getting this segfault error...can you help me
a bit?
Aside from the already mentioned C style cast
of an unsigned to a char*, you have new in what
you show but no delete. You're creating a char
array with enough space to hold what you put
in it, but no space for a terminating null. This
could be correct but it depends on what the function
mysql_query() is expecting. For example, if it's
expecting a null terminated char* and internally is
trying to strcpy() something etc. you could get
a seqfault.
Why not avoid all of this and use std::string?
You're also calling exit(1) without doing any
cleanup (though you aren't showing any
usage of this function.)
This is not usually something done
in c++ programs as it bypasses dtors and
such. Why not have your function return
a bool indicating success and let the caller
decide what to do if it fails?