std::vector in MyClass ptr causing crash on destructor - class

I have a problem in regards to a custom class I have made. The original intention was to create a particle emitter and in this emitter are two vectors to hold colors and the particles themselves.
The problem exactly is trying to destruct this custom class which functions perfectly if you do not call the destructor, which is obviously bad.
I have reduced this to a very short, compileable example.
Test.h
#include <vector>
class Test{
public:
Test();
~Test();
protected:
std::vector<int> Ints;
};
And the main.cpp:
#include "Test.h"
int main(int argc, char **argv){
Test* t;
delete[] t;
return 0;
}
In the Implementation file is just empty constructor and destructors.
Something to note is, this only happens when the "Test" is a pointer, which would preferred to be avoided.
Will provide more information if needed. Thanks in advance.

You are deleting something that hasn't allocated a memory and that too in wrong way.
Allocate memory first
Test *t = new Test;
then,
delete t; // Note no []
Also, since C++11 is tagged, prefer using smart pointers, which do the memory management for you on its own

If t is a pointer then you need to give it something to point to first, as #P0W points out. But why not just declare t to be a local (stack) variable?
#include "Test.h"
int main(int argc, char **argv){
Test t;
return 0;
}

You are not creating object Test. You have created an pointer of type Test. For a pointer you need to use the keyword "new".
Test * t = new Test();

Related

Can Sal annotate that parameter members may be mutated?

I am writing a reference-counted linked list of characters data structure in C for practice. I want to try using Sal in it to annotate function parameters for this practice.
I have an input paremeter(named This), which I want to annotate to make it clear that the specified parameter's members must be mutable in order for the function to behave as expected.
The situation is analogous to the code below.
#include <Windows.h>
typedef struct Box {
ULONG val;
} Box;
ULONG Box_decrement(_In_ Box *This) {
return InterlockedDecrement(&(This->val));
}
int main(int argc, char **argv) {
Box b = {2};
Box_decrement(&b);
return (BYTE)b.val;
};
Is there an existing Sal annotation that can be used to annotate the This parameter of the Box_increment function to make it clear from the function signature that the function modifies one or more members of the Box that has been passed to it?
Something like _InternallyMutable_(but exist):
#include <Windows.h>
typedef struct Box {
ULONG val;
} Box;
ULONG Box_decrement(_InternallyMutable_ _In_ Box *This) {
return InterlockedDecrement(&(This->val));
}
int main(int argc, char **argv) {
Box b = {2};
Box_decrement(&b);
return (BYTE)b.val;
};
Best solution so far(unfortunately, there does not seem to be any equivelent in SAL to denote Internally_mutable, there is Unchanged which is the opposite):
#include <Windows.h>
#define _Internally_mutable_(expr) _At_(expr, _Out_range_(!=, _Old_(expr)))
typedef struct Box {
ULONG val;
} Box;
ULONG Box_decrement(_In_ _InternallyMutable_(This) Box *This) {
return InterlockedDecrement(&(This->val));
}
int main(int argc, char **argv) {
Box b = {2};
Box_decrement(&b);
return (BYTE)b.val;
};
Yes! You can. SAL is a wonderful DSL that lets you do basically anything you want if you're psychic enough to infer it from the little bits in the Windows SDK. I've even in the past been able to write super simple custom annotations to detect invalid HANDLE usage with _Post_satisfies_ and friends.
This code seems to work:
_At_(value, _Out_range_(!=, _Old_(value)))
void change_value_supposed_to(int& value) noexcept {
//value += 1;
}
...Running with all native rules in code analysis, I get a warning like this:
Warning C28196 The requirement that '_Param_(1)!=(("pre"), _Param_(1))' is not satisfied. (The expression does not evaluate to true.)
(there, substitute value with your variable)
For _Internally_mutable_, I can do it in the "above the function" style of SAL:
#define _Internally_mutable_(expr) _At_(expr, _Out_range_(!=, _Old_(expr)))
_Internally_mutable_(value)
void change_value_supposed_to_internally_mutable(int& value) noexcept {
//value += 1;
(void)value;
}
...but not inline WITHOUT being repetitive, as you wanted. Not sure why right now - _Curr_ doesn't seem to be working? - I may need another layer of indirection or something. Here's what it looks like:
#define _Internally_mutable_inline_(value) _Out_range_(!=, _Old_(value))
void change_value_supposed_to_internally_mutable_inline(_Internally_mutable_inline_(value) int& value) noexcept {
//value += 1;
(void)value;
}
How I figured this out:
sal.h defines an _Unchanged_ annotation (despite doing web dev for several years now and little C++, I remembered this when I saw your question in a google alert for SAL!):
// annotation to express that a value (usually a field of a mutable class)
// is not changed by a function call
#define _Unchanged_(e) _SAL2_Source_(_Unchanged_, (e), _At_(e, _Post_equal_to_(_Old_(e)) _Const_))
...if you look at this macro closely, you'll see that it just substitutes as:
_At_(e, _Post_equal_to_(_Old_(e)) _Const_)
...and further unrolling it, you'll see _Post_equal_to_ is:
#define _Post_equal_to_(expr) _SAL2_Source_(_Post_equal_to_, (expr), _Out_range_(==, expr))
Do you see it? All it's doing is saying the _Out_range_ is equal to the expression you specify. _Out_range_ (and all the other range SAL macros) appear to accept all of the standard C operators. That behavior is not documented, but years of reading through the Windows SDK headers shows me it's intentional! Here, all we need to do is use the not equals operator with the _Old_ intrinsic, and the analyzer's solver should be able to figure it out!
_Unchanged_ itself is broken?
To my great confusion, _Unchanged_ itself seems broken:
_Unchanged_(value)
void change_value_not_supposed_to(_Inout_ int& value) noexcept {
value += 1;
}
...that produces NO warning. Without the _Inout_, code analysis is convinced that value is uninitialized on function entry. This makes no sense of course, and I'm calling this directly from main in the same file. Twiddling with inlining or link time code generation doesn't seem to help
I've played a lot with it, and various combinations of _Inout_, even _Post_satisfies_. I should file a bug, but I'm already distracted here, I'm supposed to be doing something else right now :)
Link back here if anybody does file a bug. I don't even know what the MSVC/Compiler teams use for bug reporting these days.
Fun facts
5-6 years ago I tried to convince Microsoft to open source the SAL patents! It would have been great, I would have implemented them in Clang, so we'd all be able to use it across platforms! I might have even kicked off a career in static-analysis with it. But alas, they didn't want to do it in the end. Open sourcing them would have meant they might have to support it and/or any extensions the community might have introduced, and I kinda understand why they didn't want that. It's a shame, I love SAL, and so do many others!

The rule of The Big Three

Iam confused with the below question I did the program as per my understanding but it crashes what am I doing wrong? If someone can please assist me it would be much appreciated.
my main.cpp looks like this:
#include <iostream>
#include <iomanip>
#include "Number.h"
using namespace std;
int main()
{
Number n1(10);
Number n2 = n1;
n2.printNum();
n2.addOne();
n1 = n2;
n1.printNum();
return 0;
}
Then my header file looks like this:
#include <iostream>
using namespace std;
class Number
{
int *p;
public:
Number(int);
void addOne();
void printNum();
};
And the below parts for the constructor I need to complete there where it shows comments that's the part I should complete:
#include <iostream>
#include "Number.h"
using namespace std;
Number::Number(int a1)
{
*p = a1;//write the code needed to initialise the value of the member variable with a1
}
void Number::printNum()
{
cout << "The number is " << *p << endl;
}
void Number::addOne()
{
*p++;//write the code needed to increment the value of the member variable by one.
}
Then the question asks the below what should I do to the code to use the BIG THREE?
Consider the following program. Complete the class definition (where you are asked to) and check the output. You can see that that program works without error once it is completed. However, experts suggest that in any class that uses pointers and the new operator it is better to follow the rule of The Big Three. Modify the class definition to follow the rule of The Big Three and submit the new program and the output. Demonstrate the use of this pointer.
Thank you
Rohan

C++ - Why do I have to include .cpp file along with/ instead of .h file to acces the value of a global variable in the following case?

I am trying to properly declare and define global variables in separate files and include them in a third file which deals with class declaration.
The three files are:
1) global.h
#ifndef GLOBAL_H_INCLUDED
#define GLOBAL_H_INCLUDED
extern const int marker_num;
extern const int dim;
using namespace std;
#endif // GLOBAL_H_INCLUDED
2) global.cpp
#include <iostream>
#include <cstdio>
#include <cmath>
#include "global.h"
#include "WorldState.h"
#include "Robot.h"
#include "Sensor.h"
#include "Marker.h"
constexpr const int marker_num = 10;
constexpr const int dim = (2 * marker_num) + 3;
3) WorldState.h
#ifndef WORLDSTATE_H
#define WORLDSTATE_H
#include "global.h"
#include "global.cpp"
class WorldState{
public:
WorldState(float a[], float b[dim][dim]);
get_wstate();
protected:
private:
float w_state[];
float covar_matrix[dim][dim];
};
#endif // WORLDSTATE_H
I am using the global variable dim to declare and define a multidimensional array. I have declared dim inside global.h and defined it inside global.cpp. Now, I have a class called WorldState and inside its header, I am using dim. If I comment out #include "global.cpp", it throws the following error:
C:\Users\syamp\Documents\codeblocks\slam\WorldState.h|10|error: array bound is not an integer constant before ']' token
My understanding is that including the .h file includes the corresponding .cpp as well, and that all declarations should be inside .h and all definitions should be inside .cpp. However, it doesn't seem to work in this case.
1) If I decide to include global.cpp file inside WorldState.h, isn't it bad programming practice? I am trying to write a good code not just a code that works.
2) An alternative is to define values of variable(s) dim (and marker_num) inside global.h. Is that good programming practice?
3) I believe there is something that I am missing. Kindly suggest the best method to resolve this issue. I am using codeblocks and C++11. Thanks in advance.
I am using the global variable dim to declare and define a multidimensional array.
When declaring a fixed-length array at compile-time, the value(s) of its dimension(s) must be known to the compiler, but your separation prevents the value of dim from being known to the compiler at all, so dim cannot be used to specify fixed array dimensions. Any code that uses dim will just compile into a reference to it, and then the linker will resolve the references after compilation is done. Just because dim is declared as const does not make it suitable as a compile-time constant. To do that, you must define its value in its declaration, eg:
#ifndef GLOBAL_H_INCLUDED
#define GLOBAL_H_INCLUDED
static constexpr const int marker_num = 10;
static constexpr const int dim = (2 * marker_num);
using namespace std;
#endif // GLOBAL_H_INCLUDED
Otherwise, if you keep dim's declaration and definition in separate files, you will have to dynamically allocate the array at run-time instead of statically at compile-time.
I have declared dim inside global.h and defined it inside global.cpp.
That is fine for values you don't need to use until run-time. That will not work for values you need to use at compile-time.
My understanding is that including the .h file includes the corresponding .cpp as well
That is not even remotely true. The project/makefile brings in the .cpp file when invoking the compiler. The .h file has nothing to do with that.
that all declarations should be inside .h and all definitions should be inside .cpp.
Typically yes, but not always.
If I decide to include global.cpp file inside WorldState.h, isn't it bad programming practice?
Yes.
An alternative is to define values of variable(s) dim (and marker_num) inside global.h. Is that good programming practice?
Yes, if you want to use them where compile-time constants are expected.

cannot sort a vector of objects that has array in it

Hi I am using a class that has an integer and array and creating a vector of the classes objects but I cannot sort it also don't know to store in it.
I am a BEGINNER on c++ so i just wanted to know if I am wrong and how to
do that thing
here n = no of times the program has to execute
num = to store the no. of elements in vector a
but problem loop for(j=0;j<arr[i].a.end();j++)
and also pushback is not working
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class subcont
{
public:
int num;
vector<int> a;
};
int main()
{
vector<subcont> arr(100);
int i,j,k,l,n,num1,num2;
cin>>n;
for(i=0;i<n;i++)
{
cin>>arr[i].num;
for(j=0;j<arr[i].num;j++)
{
cin>>num2;
cin>>arr[i].a.pushback(num2);
}
}
for(i=0;i<n;i++)
{
sort(arr[i].a.begin(),arr[i].a.end());
}
for(i=0;i<n;i++)
{
cout<<arr[i].num;
for(j=0;j<arr[i].a.end();j++)
cout<<arr[i].a[j];
}
return 0;
}
The problems you describe sound as if you could at least compile your code, which I can't. In fact, the compiler error messages (if one first ignores the large amount of error noise generated by unhappy templates) should hint to most important problems.
Logical problems on first sight: In for(j=0;j<k;j++) the value of k is undefined. In for(j=0;j<arr[i].a.end();a++) the a++ does not make sense.
In cin>>arr[i].a.pushback[num]; the num should probably be num2. Please check your code for more such typoes.
Your sort fails because a is a C array and not a C++ container, so a.begin() and a.end() are not defined.
Stylistic problem: While it makes life a lot easier, mayn people strictly recommend to not use using namespace std;
Additional remark: Why not use std::vector<int> in place of subcont?

Using boost::program_options with own template class possible?

I'm currently start using boost::program_options for parsing command line options as well as configuration files.
Is it possible to use own template classes as option arguments? That means, something like
#include <iostream>
#include "boost/program_options.hpp"
namespace po = boost::program_options;
template <typename T>
class MyClass
{
private:
T* m_data;
size_t m_size;
public:
MyClass( size_t size) : m_size(size) { m_data = new T[size]; }
~MyClass() { delete[] m_data; }
T get( size_t i ) { return m_data[i]; }
void set( size_t i, T value ) { m_data[i] = value; }
};
int main (int argc, const char * argv[])
{
po::options_description generic("General options");
generic.add_options() ("myclass", po::value< MyClass<int>(2) >(),
"Read MyClass");
return 0;
}
Trying to compile this I get an Semantic Issue (No matching function for call to 'value'). I guess I need to provide some casting to an generalized type but I have no real idea.
Can anybody help?
Thanks
Aeon512
I wouldn't know if boost::program_options allows the use-case you are trying, but the error you are getting is because your are trying to pass an object as a template type to po::value<>. If the size is known at compile-time, you could have the size be passed in as a template parameter.
template< typename T, size_t size >
class MyClass {
T m_data[size];
public:
// ...
};
And then use it like so:
po::value< MyClass<int, 2> >()
You should also look into using Boost.Array instead that I guess fulfills what you are trying to implement.
I would write it like this:
MyClass<int> mine(2);
generic.add_options() ("myclass", po::value(&mine), "Read MyClass");
Then all that needs to be done is to define an input stream operator like this:
std::istream& operator >>(std::istream& source, MyClass& target);
Then Boost Program Options will invoke this stream operator when the myclass option is used, and your object will be automatically populated according to that operator's implementation, rather than having to later call one of the Program Options functions to extract the value.
If you don't prefer the above syntax, something like should work too:
generic.add_options() ("myclass", po::value<MyClass<int> >()->default_value(MyClass<int>(2)), "Read MyClass");
This way you would be creating the instance of your class directly with your desired constructor argument outside of the template part where runtime behavior isn't allowed. I do not prefer this way because it's verbose and you end up needing to call more functions later to convert the value.