Hey I've been working on an SMS sending manager for gnokii in Linux but I feel I am a little bit out of my depth in relation to the memory management side of things... I'm not sure if I'm having any memory leak issues but some things make me a bit suspicious. Could anyone take a glance of my code and see if they can find any?
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <dirent.h>
using namespace std;
char* remove(char* const src, char character);
vector<string> getListOfFiles(const char* directory);
int main()
{
string DirIn = "/var/gsm/in/", DirOut = "/var/gsm/out/", DirSent = "/var/gsm/sent/", DirFail = "/var/gsm/fail/";
vector<string> Filenames = getListOfFiles(DirOut.c_str());
for(unsigned int i = 0; i < Filenames.size(); i++)
{
fstream SMSFile((DirOut + Filenames.at(i)).c_str());
if(!SMSFile.fail())
{
char NumberLine[64];
SMSFile.getline(NumberLine, 64);
string Number = NumberLine;
Number = Number.substr(8);
if(Number.length() == 10)
{
cout << "Number is OK" << endl;
}
else
{
cout << "Number is Wrong" << endl;
}
cout << Number << endl;
char MsgLine[160];
SMSFile.getline(MsgLine, 160);
// Remove ", ', carriage returns and new lines
strcpy(MsgLine, remove(MsgLine, '\n'));
strcpy(MsgLine, remove(MsgLine, '\r'));
strcpy(MsgLine, remove(MsgLine, '\''));
strcpy(MsgLine, remove(MsgLine, '"'));
string Msg = MsgLine;
if(!system(("echo \"" + Msg + "\" | gnokii --sendsms " + Number).c_str()))
{
cout << "SMS Sent to " << Number << "!" << endl;
system(("mv " + DirOut + Filenames.at(i) + " " + DirSent).c_str());
}
else
{
cout << "SMS Failed to " << Number << "!" << endl;
system(("mv " + DirOut + Filenames.at(i) + " " + DirFail).c_str());
}
}
}
else
{
cout << "Unable to open the file" << endl;
}
}
return 0;
};
vector<string> getListOfFiles(const char* directory)
{
vector<string> Filenames;
DIR* dirHandle;
struct dirent* dirEntry;
dirHandle = opendir(directory);
if(dirHandle != NULL)
{
while((dirEntry = readdir(dirHandle)))
{
if(dirEntry->d_type != DT_DIR)
{
Filenames.push_back(dirEntry->d_name);
}
}
}
return Filenames;
}
char* remove(char* const src, char character)
{
char* s = src;
int occurences = 0, length = 0;
while(*s)
{
if(*s == character)
occurences++;
length++;
s++;
}
char* result = new char[length - occurences + 1];
char* resultptr = result;
s = src;
while(*s)
{
if(*s != character)
{
*resultptr = *s;
resultptr++;
}
s++;
}
*resultptr = '\0';
return result;
}
I think mainly around the passing of variables between functions, some of them are local such as the vector, so if I return it is the memory marked for deletion so that when I try to access it from outside the function it'll stuff up?
Thanks heaps