I am defining a new C++ class whose what
method returns a char*
type with the value of an integer passed as constructor.
Originally I did it using string
class and returning the string data from what
.
Then I am trying to use char*
type in the following code:
/* Define the exception here */
class BadLengthException: public exception
{
public:
BadLengthException(int strLength)
{
strLen = strLength;
res = (char*)malloc(strLength+1);
int resultSize = sprintf(res, "%d", strLen);
}
~BadLengthException() throw()
{
free(res);
}
virtual const char* what() const throw()
{
return res;
}
private:
int strLen;
char* res;
};
but I am having problem when freeing the malloc
allocated variable: it gives this Exception:
pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
So why is that? Where and how should I free a dyanmic allocated variable in a Exception class?
EDIT
Here a minimal working complete example. The program will ask for user input. The first is a number specifying the number of the following inputs. The other inputs will be strings. The above exception will be raised if the string is shorter than 5.
Just enter: 1
and then Me
for example
#include <iostream>
#include <string>
#include <sstream>
#include <exception>
using namespace std;
/* Define the exception here */
class BadLengthException: public exception
{
public:
BadLengthException(int strLength)
{
strLen = strLength;
res = (char*)malloc(strLength+1);
int resultSize = sprintf(res, "%d", strLen);
}
~BadLengthException() throw()
{
free(res);
}
virtual const char* what() const throw()
{
return res;
}
private:
int strLen;
char* res;
};
bool checkUsername(string username) {
bool isValid = true;
int n = username.length();
if(n < 5) {
throw BadLengthException(n);
}
for(int i = 0; i < n-1; i++) {
if(username[i] == 'w' && username[i+1] == 'w') {
isValid = false;
}
}
return isValid;
}
int main() {
int T; cin >> T;
while(T--) {
string username;
cin >> username;
try {
bool isValid = checkUsername(username);
if(isValid) {
cout << "Valid" << '\n';
} else {
cout << "Invalid" << '\n';
}
} catch (BadLengthException e) {
cout << "Too short: " << e.what() << '\n';
}
}
return 0;
}
EDIT 2
The original class using string is the following: this one does work
class BadLengthException: public exception
{
public:
BadLengthException(int strLength)
{
res = to_string(strLength);
}
virtual const char* what() const throw()
{
return res.c_str();
}
private:
string res;
};