I am trying to learn gecode and am trying to get the example found here to work.
// To use integer variables and constraints
#include <gecode/int.hh>
// To make modeling more comfortable
#include <gecode/minimodel.hh> // To use search engines
#include <gecode/search.hh>
// To avoid typing Gecode:: all the time
using namespace Gecode;
class SendMoreMoney : public Space {
protected:
IntVarArray x;
public:
SendMoreMoney() : x(*this, 8, 0, 9) {
IntVar s(x[0]), e(x[1]), n(x[2]), d(x[3]), m(x[4]), o(x[5]), r(x[6]),
y(x[7]);
rel(*this, s != 0);
rel(*this, m != 0);
distinct(*this, x);
rel(*this,
1000 * s + 100 * e + 10 * n + d + 1000 * m + 100 * o + 10 * r + e ==
10000 * m + 1000 * o + 100 * n + 10 * e + y);
branch(*this, x, INT_VAR_SIZE_MIN(), INT_VAL_MIN());
}
SendMoreMoney(SendMoreMoney& s) : Space(s) { x.update(*this, s.x); }
virtual Space* copy() { return new SendMoreMoney(*this); }
void print() const { std::cout << x << std::endl; }
};
int main() {
SendMoreMoney* m = new SendMoreMoney;
DFS<SendMoreMoney> e(m);
delete m;
while (SendMoreMoney s = e.next()) {
s->print();
delete s;
}
}
I end up with the following compilation errors.
error: no matching function for call to 'Gecode::IntVarArray::update(SendMoreMoney&, Gecode::IntVarArray&)'
27 | x.update(*this, s.x);
| ^
and
error: invalid new-expression of abstract class type 'SendMoreMoney'
30 | return new SendMoreMoney(*this);
|
I do not understand where these come from. IntVarArray certainly has an update function whose first argument is a Space object and SendMoreMoney inherits from Space so what is the problem? This code is verbatim from the example I found so presumably it should work as-is.
e.next() returns a pointer of the cloned space (SendMoreMoney). You must use while (SendMoreMoney* s = e.next())
Related
I am a newbie in regex, I try to write a C# application that replace all of old cast style of c++ file to static_cast style.
For example:
(void)memcpy(&a[0],(void * )hihi, (UBYTE) V_SIZE);
(void) memcpy((VOID*)abc, (const VOID*) dafa, (uint8)NUMBER_SIZE);
(void )memcpy(
(void *)p,
&abc, (uint8)DATE_SIZE);
I expect all of them should be
static_cast<void>(memcpy(&a[0], static_cast<void * >(hihi), static_cast<UBYTE>( V_SIZE)));
static_cast<void> memcpy(static_cast<VOID*>(abc), static_cast<const VOID*> (hihi), static_cast<uint8>(NUMBER_SIZE));
static_cast<void >memcpy(
static_cast<void *>(p),
&abc, static_cast<uint8>(DATE_SIZE));
I also investigate and try with this one
List<string> castTypeList = new List<string>
{"void", "void *", "UBYTE", "uint8", "VOID*", "uint8" };
// Fix qacpp-4.7.0-3080 This expression uses old style casts
// Only apply for cpp source file (.cpp)
if ((Path.GetExtension(sourceFile) == ".cpp"))
{
foreach (string e in castTypeList)
{
File.WriteAllText(sourceFile, Regex.Replace(
File.ReadAllText(sourceFile),
#"\(" + e + #"\)([^):;\r\n},]*)",
"static_cast<" + e + #">($1)"));
}
}
The result look good, but not perfect, some string can't match and replace (You can see below picture). Is there any better solution or better idea to handle it?
You can match and replace with the following pattern until no match is found:
(?i)\(\s*((?:const\s+)?(?:u?(?:byte|int)\d*|void)(?:\s*\*)?)\s*\)\s*(\w+(?:\((?>[^()]+|(?<c>)\(|(?<-c>)\))*\))?)
See the regex demo.
In C#, you can use
var text = #"(void)memcpy(&a[0],(void * )hihi, (UBYTE) V_SIZE);\n(void) memcpy((VOID*)abc, (const VOID*) dafa, (uint8)NUMBER_SIZE);\n(void )memcpy(\n (void *)p,\n &abc, (uint8)DATE_SIZE)";
var pattern = #"(?i)\(\s*((?:const\s+)?(?:u?(?:byte|int)\d*|void)(?:\s*\*)?)\s*\)\s*(\w+(?:\((?>[^()]+|(?<c>)\(|(?<-c>)\))*\))?)";
var tmp = string.Empty;
do
{
tmp = text;
text = Regex.Replace(text, pattern, "static_cast<$1>($2)");
}
while (text != tmp);
Console.WriteLine(text);
See the C# demo. Output:
static_cast<void>(memcpy(&a[0],static_cast<void *>(hihi), static_cast<UBYTE>(V_SIZE)));
static_cast<void>(memcpy(static_cast<VOID*>(abc), static_cast<const VOID*>(dafa), static_cast<uint8>(NUMBER_SIZE)));
static_cast<void>(memcpy(
static_cast<void *>(p),
&abc, static_cast<uint8>(DATE_SIZE)));
I have finally found the solution for myself.
List<string> part_one_CastTypeList = new List<string>
{"void", "void "};
List<string> part_two_CastTypeList = new List<string>
{"void * ", "UBYTE", "VOID*", "const VOID*", "uint8", "void *"};
if ((Path.GetExtension(sourceFile) == ".cpp"))
{
foreach (string e in part_one_CastTypeList)
{
string castType = null;
foreach (char c in e)
{
castType = castType + '[' + c + ']';
}
// Match multi pattern, variant is inside function (Applicable for void type)
// i.e (void)memcpy((FLOAT)a, (void *) b, (uint8)c)
// ==> static_cast<void>memcpy((FLOAT)a, (void *) b, (uint8)c)
File.WriteAllText(sourceFile, Regex.Replace(
File.ReadAllText(sourceFile),
#"\(" + castType + #"\)([^;\r\n}]*)(\);)",
"static_cast<" + e + #">($1)$2"));
}
foreach (string e in part_two_CastTypeList)
{
string castType = null;
foreach(char c in e)
{
castType = castType + '[' + c + ']';
}
// Match single pattern, variant is not inside function (Not applicable for void type)
// i.e (uint8)0x00,(uint16)0x01, (SW) 0x02
// ==> static_cast<uint8>(0x00),static_cast<uint16>(0x01), static_cast<SW>(0x02),
File.WriteAllText(sourceFile, Regex.Replace(
File.ReadAllText(sourceFile),
#"\(" + castType + #"\)([^:\/;)\r\n},]*)",
"static_cast<" + e + #">($1)"));
}
}
I will separate regex to 2 part. Part 1 (first for loop) will match the type cast of the function. After first for loop completed, all cast type of the function should be replaced like below
static_cast<void>(memcpy(&a[0],(void * )hihi, (UBYTE) V_SIZE));
static_cast<void>( memcpy((VOID*)abc, (const VOID*) dafa, (uint8)NUMBER_SIZE));
static_cast<void >(memcpy(
(void *)p,
&abc, (uint8)DATE_SIZE));
part 2 (second for loop) will match the type cast of the variant and replace all of the rest like below
static_cast<void>(memcpy(&a[0],static_cast<void * >(hihi), static_cast<UBYTE>( V_SIZE)));
static_cast<void>( memcpy(static_cast<VOID*>(abc), static_cast<const VOID*>( dafa), static_cast<uint8>(NUMBER_SIZE)));
static_cast<void >(memcpy(
static_cast<void *>(p),
&abc, static_cast<uint8>(DATE_SIZE)));
It's not perfect 100% but I try with many source files and it look good, it can match up to 99% :))
Reliably matching old-style casts is impossible with a regex, because you can't tell for sure what's a type and what's not. As proof, consider this C++ file:
#include "somefile.h"
void f(sometype_t x) {
g((something)*x);
h((somethingelse)(x));
}
If something is a type, then the line with it is a cast, but if it's a variable, then it isn't. Similarly, if somethingelse is a type, then the line with it is a cast, but if it's a function, then it isn't. Further reading: https://en.wikipedia.org/wiki/Lexer_hack
To really hammer the point home, consider this other C++ file:
void g(long);
void h(char *);
template<int N>
struct SomeStruct {
typedef int *sometype_t;
typedef short something;
typedef char *somethingelse;
};
template<>
struct SomeStruct<42> {
typedef int sometype_t;
short something;
char *somethingelse(sometype_t);
};
constexpr int a = 12300 + 45;
constexpr int b = 40 + 2;
struct Child1 : SomeStruct<a> {
void f(sometype_t x) {
g((something)*x);
h((somethingelse)(x));
}
};
struct Child2 : SomeStruct<b> {
void f(sometype_t x) {
g((something)*x);
h((somethingelse)(x));
}
};
Now it should be clear that the only way to know whether or not those things are casts is by first evaluating arbitrary constexpr expressions, which are Turing-complete.
I encountered a strange behavior in my C++ program that I don't understand and I don't know how to search for more information. So I ask for advice here hoping someone might know.
I have a class Interface that has a 2 dimensional vector that I initialize in the header :
class Interface {
public:
// code...
const unsigned short int SIZE_X_ = 64;
const unsigned short int SIZE_Y_ = 32;
std::vector<std::vector<bool>> screen_memory_ =
std::vector<std::vector<bool>>(SIZE_X_, std::vector<bool>(SIZE_Y_, false));
// code...
};
Here I expect that I have a SIZE_X_ x SIZE_Y_ vector filled with false booleans.
Later in my program I loop at a fixed rate like so :
void Emulator::loop() {
const milliseconds intervalPeriodMillis{static_cast<int>((1. / FREQ) * 1000)};
//Initialize the chrono timepoint & duration objects we'll be //using over & over inside our sleep loop
system_clock::time_point currentStartTime{system_clock::now()};
system_clock::time_point nextStartTime{currentStartTime};
while (!stop) {
currentStartTime = system_clock::now();
nextStartTime = currentStartTime + intervalPeriodMillis;
// ---- Stuff happens here ----
registers_->trigger_timers();
interface_->toogle_buzzer();
interface_->poll_events();
interface_->get_keys();
romParser_->step();
romParser_->decode();
// ---- ------------------ ----
stop = stop || interface_->requests_close();
std::this_thread::sleep_until(nextStartTime);
}
}
But then during the execution I get a segmentation fault
[1] 7585 segmentation fault (core dumped) ./CHIP8 coin.ch8
I checked with the debugger and some part of the screen_memory_ cannot be accessed anymore. And it seems to happen at random time.
But when I put the initialization of the vector in the constructor body like so :
Interface::Interface(const std::shared_ptr<reg::RegisterManager> & registers, bool hidden)
: registers_(registers) {
// code ...
screen_memory_ =
std::vector<std::vector<bool>>(SIZE_X_, std::vector<bool>(SIZE_Y_, false));
// code ...
}
The segmentation fault doesn't happen anymore. So the solution is just to initialize the vector in the constructor body.
But why ? what is happening there ?
I don't understand what I did wrong, I'm sure someone knows.
Thanks for your help !
[Edit] I found the source of the bug (Or at least what to change so it doesnt give me a segfault anymore).
In my class Interface I use the SDL and SDL_audio libraries to create the display and the buzzer sound. Have a special look where I set the callback want_.callback, the callback Interface::forward_audio_callback and Interface::audio_callback. Here's the code :
// (c) 2021 Maxandre Ogeret
// Licensed under MIT License
#include "Interface.h"
Interface::Interface(const std::shared_ptr<reg::RegisterManager> & registers, bool hidden)
: registers_(registers) {
if (SDL_Init(SDL_INIT_AUDIO != 0) || SDL_Init(SDL_INIT_VIDEO) != 0) {
throw std::runtime_error("Unable to initialize rendering engine.");
}
want_.freq = SAMPLE_RATE;
want_.format = AUDIO_S16SYS;
want_.channels = 1;
want_.samples = 2048;
want_.callback = Interface::forward_audio_callback;
want_.userdata = &sound_userdata_;
if (SDL_OpenAudio(&want_, &have_) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_AUDIO, "Failed to open audio: %s", SDL_GetError());
}
if (want_.format != have_.format) {
SDL_LogError(SDL_LOG_CATEGORY_AUDIO, "Failed to get the desired AudioSpec");
}
window = SDL_CreateWindow("CHIP8", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
SIZE_X_ * SIZE_MULTIPLIER_, SIZE_Y_ * SIZE_MULTIPLIER_,
hidden ? SDL_WINDOW_HIDDEN : 0);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE);
bpp_ = SDL_GetWindowSurface(window)->format->BytesPerPixel;
SDL_Delay(1000);
// screen_memory_ = std::vector<std::vector<bool>>(SIZE_X_, std::vector<bool>(SIZE_Y_, false));
}
Interface::~Interface() {
SDL_CloseAudio();
SDL_DestroyWindow(window);
SDL_Quit();
}
// code ...
void Interface::audio_callback(void * user_data, Uint8 * raw_buffer, int bytes) {
audio_buffer_ = reinterpret_cast<Sint16 *>(raw_buffer);
sample_length_ = bytes / 2;
int & sample_nr(*(int *) user_data);
for (int i = 0; i < sample_length_; i++, sample_nr++) {
double time = (double) sample_nr / (double) SAMPLE_RATE;
audio_buffer_[i] = static_cast<Sint16>(
AMPLITUDE * (2 * (2 * floor(220.0f * time) - floor(2 * 220.0f * time)) + 1));
}
}
void Interface::forward_audio_callback(void * user_data, Uint8 * raw_buffer, int bytes) {
static_cast<Interface *>(user_data)->audio_callback(user_data, raw_buffer, bytes);
}
}
In the function Interface::audio_callback, replacing the class variable assignation :
sample_length_ = bytes / 2;
By an int creation and assignation :
int sample_length = bytes / 2;
which gives :
void Interface::audio_callback(void * user_data, Uint8 * raw_buffer, int bytes) {
audio_buffer_ = reinterpret_cast<Sint16 *>(raw_buffer);
int sample_length = bytes / 2;
int &sample_nr(*(int*)user_data);
for(int i = 0; i < sample_length; i++, sample_nr++)
{
double time = (double)sample_nr / (double)SAMPLE_RATE;
audio_buffer_[i] = (Sint16)(AMPLITUDE * sin(2.0f * M_PI * 441.0f * time)); // render 441 HZ sine wave
}
}
The class variable sample_length_ is defined and initialized as private in the header like so :
int sample_length_ = 0;
So I had an idea and I created the variable sample_length_ as public and it works ! So the problem was definitely a scope problem of the class variable sample_length_. But it doesn't explain why the segfault disappeared when I moved the init of some other variable in the class constructor... Did I hit some undefined behavior with my callback ?
Thanks for reading me !
I just started learning C++ and trying to port some PHP code at the moment.
I am getting a segfault from this piece of code :
class Color {
public:
// Props
int r;
int g;
int b;
int a;
// Constructor
Color (int r, int g, int b, int a) {
this -> r = r;
this -> g = g;
this -> b = b;
this -> a = a;
};
// Destructor
~Color () {
delete this;
};
// Mix 2 colors
void mixColor (const Color& c) {
this -> r = (this -> r + c.r) / 2;
this -> g = (this -> g + c.g) / 2;
this -> b = (this -> b + c.b) / 2;
this -> a = (this -> a + c.a) / 2;
};
};
And in main file :
int main () {
Color myColor (10, 20, 30, 40);
return 1;
}
Any idea what causes it ?
Thanks.
To expand on the current answers.
The reason you can't be using delete in this case is that by not using the 'new' keyword you created the object on the stack, and it will be automatically destroyed when the scope it was created in is no longer relevant.
This is useful for an object such as the one you posted, since its small and more importantly, it isn't managing any sort of memory internally, which could lead to some memory leaks.
Also since everything inside the class is public, you might consider making it a struct.
You should only call delete on things you allocated with new. You didn't allocate this with a new, so you shouldn't call delete on it.
This is sort of a design doubt .
Scenario: I have an array which contain some integer elements . This array is populated by 1 module (.so) in my code base say X. It is then shared to another module say Y (.so) . At run time X module identifies that module Y would need to work on few fields of the array and modify it and that was the reason X shared the array to Y . ( Both these so are consumed into one binary .)
Once Y returns the module X prints the array .
Problem : How can I enforce programatically that module Y does not modify any other array index other than the one identified by X . SInce the whole array is passed between modules i cant make it const as then Y would not be able to change any field . You can say i want to enforce const-ness for few fields identified at run time .
How about this:
template <class T> class CProtectedArray {
private:
T* m_aItems;
unsigned int* m_aMask;
public:
CProtectedArray(int cElem, bool fInitialProtect) : m_aItems(NULL) {
int cbElem = sizeof(T)*cElem;
int cbMask = sizeof(int)*(cElem+31)/32;
m_aItems = (T*)malloc(cbElem + cbMask);
m_aMask = (unsigned int*)(m_aItems + cElem);
memset(m_aItems, 0, cbElem);
memset(m_aMask, fInitialProtect ? -1 : 0, cbMask);
}
~CProtectedArray() {
if (m_aItems)
free(m_aItems);
}
bool IsProtected(int iItem) { return !!(m_aMask[iItem>>5] & (1<<(iItem&31))); }
void Protect(int iItem) { m_aMask[iItem>>5] |= 1<<(iItem&31); }
void UnProtect(int iItem) { m_aMask[iItem>>5] &= ~(1<<(iItem&31)); }
void Set(int iItem, T val) {
if (!IsProtected(iItem))
m_aItems[iItem] = val;
}
};
int main(int argc, char* argv[])
{
CProtectedArray<int> A(100, true);
bool f = A.IsProtected(30); // f = true
A.Set(30, 23); // nothing happens
A.UnProtect(30);
f = A.IsProtected(30); // f = false
A.Set(30, 24); // sets element 30 to 24
A.Protect(30);
f = A.IsProtected(30); // f = true
A.Set(30, 25); // nothing happens
}
Alternative 1, reusing a temporary variable:
Sticker sticker;
sticker.x = x + foreground.x;
sticker.y = foreground.y;
sticker.width = foreground.width;
sticker.height = foreground.height;
board.push_back(sticker);
sticker.x = x + outline.x;
sticker.y = outline.y;
sticker.width = outline.width;
sticker.height = outline.height;
board.push_back(sticker);
Alternative 2, scoping the temporary variable:
{
Sticker sticker;
sticker.x = x + foreground.x;
sticker.y = foreground.y;
sticker.width = foreground.width;
sticker.height = foreground.height;
board.push_back(sticker);
}
{
Sticker sticker;
sticker.x = x + outline.x;
sticker.y = outline.y;
sticker.width = outline.width;
sticker.height = outline.height;
board.push_back(sticker);
}
Alternative 3, writing straight to the vector memory:
{
board.push_back(Sticker());
Sticker &sticker = board.back();
sticker.x = x + foreground.x;
sticker.y = foreground.y;
sticker.width = foreground.width;
sticker.height = foreground.height;
}
{
board.push_back(Sticker());
Sticker &sticker = board.back();
sticker.x = x + outline.x;
sticker.y = outline.y;
sticker.width = outline.width;
sticker.height = outline.height;
}
Which approach do you prefer?
Edit: For the sake of this discussion, assume that the assignments have to be made one by one outside of a constructor
My option - give Sticker a constructor that takes the parameters. then:
board.push_back( Sticker( outline.x, foo.bar, etc. ) );
Edit: Code to illustrate constructor parameter names:
#include <iostream>
using namespace std;
struct S {
int a, b;
S( int a, int b ) : a(a), b(b) {
}
};
int main() {
S s( 1, 2);
cout << s.a << " " << s.b << endl;
}
board.resize(sticker_count);
Then iterate through all the vector and set parameters.
Alternative 1. Why create a scope just for a variable? There is usually an enclosing scope nearby (at the minimum, you should keep your functions/procedures small so that will scope it).
Why? You can create a shorter variable name e.g. st in this case. Since the assignment will be nearby there should be no loss in clarity. Actually it will look simpler and cleaner.
Also, if the vector needs to be dereferenced/accessed from several other levels of indirection, then it will also simplify the code.
How about winforms style:
// Class members
Sticker sticker1;
Sticker sticker2;
Board board;
// Initialization
void InitBoard()
{
sticker1.x = x + foreground.x;
sticker1.y = foreground.y;
sticker1.width = foreground.width;
sticker1.height = foreground.height;
sticker2.x = x + outline.x;
sticker2.y = outline.y;
sticker2.width = outline.width;
sticker2.height = outline.height;
// Add to board
board.push_back(sticker1);
board.push_back(sticker2);
}