I'm trying to write a simple twitter-like program and when I want to new an object of my classes I get segmentation fault error here is part of my classes:
//Tweet.hpp file
class Tweet {
private:
int tweetId;
string text;
string tweeterUser;
int numOfLikes;
int numOfRetweets;
vector<string> tags;
vector<Tweet*> commentsOrReplies;
vector<string> mentions;
public:
Tweet(int _jeekId, string _text, string _user) : jeekId(_tweetId),
text(_text), tweeterUser(_user),
numOfRejeeks(0), numOfLikes(0) {}
Tweet(int _tweetId, string _user) : tweetId(_jeekId), text(" "),
tweeterUser(_user) {}
~Tweet() {}
};
and this is where I want to new an instance of it:
//Tweeter.hpp file
class Tweeter {
private:
vector<Tweet*> allTweets;
vector<User*> allUsers;
User* currentUser;
Tweet* currenttweet;
public:
vector<User*> getUsers() { return allUsers;}
Tweeter() {}
~Tweeter() {}
void tweet(string tweetText, int uniqueId);
};
//Tweeter.cpp file
void Tweeter::tweet(string tweetText, int uniqueId) {
int currentUserPos = findTweetPosByTweetId(allUsers,
currentTweet->getTweetId());
// Problem is in this line :
Tweet* j = new Tweet(uniqueId, tweetText,
allUsers[currentUserPos]->getUsername());
currentTweet = j;
}
I'm probably sure that the problem comes from the return value of findTweetPosByTweetId() function whenever it can't find wantedTweet. which it's body is:
int findTweetPosByTweetId(vector<Tweet*> allTweets, int
requestedTweetId) {
int pos;
for(int j = 0 ; j < allTweets.size() ; j++)
if(allTweets[j]->getTweetId() == requestedTweetId)
pos = j;
return pos;
}
but how can I edit it to return -1 whenever it couldn't find the Tweet, I've tried this but it was unsuccessful:
int findTweetPosByTweetId(vector<Tweet*> allTweets, int
requestedTweetId) {
int pos;
for(int j = 0 ; j < allTweets.size() ; j++){
if(allTweets[j]->getTweetId() == requestedTweetId)
pos = j;
else pos = -1;
}
return pos;
}
compile with debug option on (-g for g++) , run in gdb and you will immediately have the offending line of code. If you're new to gdb (assuming you're on Linux) , use the -tui interface... makes life so much easier when navigating.
Hope that helps.
G