Let's say I've got a method called addPoint that accepts an object as an argument like so...
addPoint(Point a(2), Point b(5));
...would this be the correct way of using the addPoint method with pointers?
1 2 3
Point* a = new Point(2);
Point* b = new Point(5);
addPoint(*a, *b);
For me, the above only works if the Point objects are initialized inside the same method as addPoint. If I initialize them in a constructor and then try using addPoint in another method, the program segfaults.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Line::Line()
{
a = new Point(2); //header file: Point* a;
b = new Point(5); //header file: Point *b;
}
int Line::getAddedPoints()
{
addPoints(*a, *b); //segfaults
}
int Line::getAddedPoints2()
{
a = new Point(2);
b = new Point(5);
addPoints(*a, *b); //works fine
}
I suppose, but you need to remember to delete them when you are done...however, if a and b are members of the Line class, then getAddedPoints() shouldn't segfault unless you are doing something weird. What does addPoints() look like?
The above is a running example of something similar to what you've described. I unfortunately cannot pinpoint the exact location the segfault would happen without more information.
Well, I'm actually working with a tr1::regex class. Here's the actual code that's giving me the problem. I've stripped out everything that wasn't necessary and pointed out exactly where it segfaults.
#include "stdafx.h"
#include "Parser.h"
Parser::Parser()
{
patternA = new tr1::regex("testA");
patternB = new tr1::regex("testB");
patternC = new tr1::regex("testC");
//etc...
}
string Parser::getMatchA(string str)
{
return findmatch(str, patternA);
}
string Parser::getMatchB(string str)
{
return findmatch(str, patternB);
}
string Parser::getMatchC(string str)
{
return findmatch(str, patternC);
}
//etc...
//private method
string Parser::findmatch(string str, tr1::regex* pattern)
{
tr1::smatch result;
if (tr1::regex_search(str, result, *pattern)) //segfaults here
return result[1]; //does not segfault if '*pattern' is replaced with 'tr1::regex("test")'
elsereturn"";
}
When I do a getMatch method, the program segfaults. Otherwise if I do it within a try-catch block, I get an exception along the lines of "corrupt pattern". The actual patterns I'm using have been tested, so I'm sure that they aren't corrupt.