I am coming from java to c++ and I am trying to adjust to the nuances(more like huge differences). I am getting a seg fault error and can not figure out why. I have three files, unit_test1.cpp which holds my main(), card.cpp and card.h. I've been fight this for sometime now, any help would be greatly appreciated.
test = (Card *) malloc(sizeof(Card)); This allocates memory for Card. It does not creates instance of variable.
In Java it is something like
1 2
ByteBuffer cc = ByteBuffer.allocateDirect(/*Get size of card*/);
Card test = /*Somehow make it point to cc buffer*/;
In C++ you should use new for class dynamic allocation (allocalion and construction using malloc is possible, but unwieldy): Card* test = new Card; //looks familiar, isn't it?
However in C++ you should prefer automatic variables instead:
1 2
Card test; //That's all. It is ready to use
test.getCard();
And if for some reason you need dynamic variables, consider using smart pointers:
1 2 3
std::unique_ptr<Card> test(new Card);
//or (C++14)
auto test = std::make_unique<Card>();
Smart pointers automatically delete corresponding variable when owner (all owners for shared pointers) is destoyed, saving yourself from hassle of manual memory management.
I am currently working with bash so I am using c and c++. The lines are getting blurred, I suppose that is why I tried to use malloc instead of using automatic variables.
Here you declared getCard() as returning string, but did not return anything. It might lead to problems. Either declare it as void function, or actually return string:
It looks like you did not enable warning in your compiler. I highly recommend to do so (as majority of errors can be fixed just by looking at warnings). Method of enabling warnings differs between different compilers/IDE, so say what you use if you will have any problems with that.
Thanks that worked. I did as you said and applied a warning to my compile and it pointed out exactly that issue. I used -Wall, should I be using other warning flags when compiling.
Currently, Compile - g++ -Wall unit_test1.cpp Card.h Card.cpp
-Wextra /*Yes, GCC has own idea what -Wall means*/
-pedantic /*or preferably -pedantic-errors */
-std=c++11 /*or -std=c++1y to enable latest C++ standard. */
Additional note to MiiniPaa's response involving "new". Use "new" to allocate the Card pointer and "delete" to deallocate to the memory allocated by new. Without "delete" the memory won't be freed until the end of the program so in a more complex program with many allocations you will have a non-trivial memory leak.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main()
{
// allocate Card and create instance
Card* test = new Card;
test->printCard();
std::string tmp = test->getCard();
std::cout << tmp << std::endl;
// deallocate (C++ does not do automatic garbage collection like Java does)
delete test;
return 0;