CUDD using not-gate - cudd

I am trying to build a BDD for monotone multiplication and need to use the negation of the input bits.
I am using the following code:
DdNode *x[N], *y[N], *nx[N], *ny[N];
gbm = Cudd_Init(0,0,CUDD_UNIQUE_SLOTS,CUDD_CACHE_SLOTS,0); /* Initialize a new BDD manager. */
for(k=0;k<N;k++)
{
x[k] = Cudd_bddNewVar(gbm);
nx[k] = Cudd_Not(x[k]);
y[k] = Cudd_bddNewVar(gbm);
ny[k] = Cudd_Not(y[k]);
}
The error that I am getting is:
cuddGarbageCollect: problem in table 0
dead count != deleted
This problem is often due to a missing call to Cudd_Ref
or to an extra call to Cudd_RecursiveDeref.
See the CUDD Programmer's Guide for additional details.Aborted (core dumped)
The multiplier compiles and runs fine when I am using
x[k] = Cudd_bddNewVar(gbm);
nx[k] = Cudd_bddNewVar(gbm);
y[k] = Cudd_bddNewVar(gbm);
ny[k] = Cudd_bddNewVar(gbm);
What should I do, the manual does not help not truing to ref x[k],nx[k]...

Every BDD node that is not referenced is subject to deletion by any Cudd operation. If you want to make sure that all nodes stored in your array remain valid, you need to Cudd_Ref them immediately after they are returned by CUDD. Hence, you need to correct your code to:
for(k=0;k<N;k++)
{
x[k] = Cudd_bddNewVar(gbm);
Cudd_Ref(x[k]);
nx[k] = Cudd_Not(x[k]);
Cudd_Ref(nx[k]);
y[k] = Cudd_bddNewVar(gbm);
Cudd_Ref(y[k]);
ny[k] = Cudd_Not(y[k]);
Cudd_Ref(yn[k]);
}
Before deallocating the Cudd manager, you then need to dereference the nodes:
for(k=0;k<N;k++)
{
Cudd_RecursiveDeref(gbm,x[k]);
Cudd_RecursiveDeref(gbm,nx[k]);
Cudd_RecursiveDeref(gbm,y[k]);
Cudd_RecursiveDeref(gbm,ny[k]);
}
Note that the fact that your code works when allocating more variables does not show that referencing is not needed. It may simply be that you do not ever use enough nodes for the garbage collector to trigger -- and before that, the problem is not detected.

Related

how to handle read access violation?

sorry for avoiding you guys
i have a problem with reverse function in circular linked list.
void reverse() {
int num = many;
node* current = head;
node* previous = 0;
while (num != 0) {
cout << "1" << '\t';
node* r = previous;
previous = current;
current = current->next;
previous->next = r;
num--;
}
head = previous;
}
in this func after 2 while sentence
problem comes up in line that current = current->next;
(exception throw : read access violation,
current was 0xDDDDDDDD)
how to handle it??
This is from Visual Studio trying to help you (and succeeding, IMO).
As Mark Ingraham pointed out in another answer a long time ago, Visual Studio's runtime library will fill a block of data with 0xDDDDDDDD when you release a block of heap memory.
So, although you haven't shown any code that's deleting from your list, if there is such code, that's probably the first place to look--at least at first glance, it looks like there's a fair chance that when you try erase a node from the list, you're deleting the memory the node lives in, but still leaving a pointer to that deleted memory.
It's also possible (but less likely, IMO) that you're just using memory without initializing it--and you happen to be hitting a block of memory that was previously allocated and then released back to the heap manager.
The bottom line, however, is that you don't "handle" the access violation. Instead, you need to find the bug in your code that's leading to the access violation happening, and fix it so that doesn't happen any more.

Lock-free programming: reordering and memory order semantics

I am trying to find my feet in lock-free programming. Having read different explanations for memory ordering semantics, I would like to clear up what possible reordering may happen. As far as I understood, instructions may be reordered by the compiler (due to optimization when the program is compiled) and CPU (at runtime?).
For the relaxed semantics cpp reference provides the following example:
// Thread 1:
r1 = y.load(memory_order_relaxed); // A
x.store(r1, memory_order_relaxed); // B
// Thread 2:
r2 = x.load(memory_order_relaxed); // C
y.store(42, memory_order_relaxed); // D
It is said that with x and y initially zero the code is allowed to produce r1 == r2 == 42 because, although A is sequenced-before B within thread 1 and C is sequenced before D within thread 2, nothing prevents D from appearing before A in the modification order of y, and B from appearing before C in the modification order of x. How could that happen? Does it imply that C and D get reordered, so the execution order would be DABC? Is it allowed to reorder A and B?
For the acquire-release semantics there is the following sample code:
std::atomic<std::string*> ptr;
int data;
void producer()
{
std::string* p = new std::string("Hello");
data = 42;
ptr.store(p, std::memory_order_release);
}
void consumer()
{
std::string* p2;
while (!(p2 = ptr.load(std::memory_order_acquire)))
;
assert(*p2 == "Hello"); // never fires
assert(data == 42); // never fires
}
I'm wondering what if we used relaxed memory order instead of acquire? I guess, the value of data could be read before p2 = ptr.load(std::memory_order_relaxed), but what about p2?
Finally, why it is fine to use relaxed memory order in this case?
template<typename T>
class stack
{
std::atomic<node<T>*> head;
public:
void push(const T& data)
{
node<T>* new_node = new node<T>(data);
// put the current value of head into new_node->next
new_node->next = head.load(std::memory_order_relaxed);
// now make new_node the new head, but if the head
// is no longer what's stored in new_node->next
// (some other thread must have inserted a node just now)
// then put that new head into new_node->next and try again
while(!head.compare_exchange_weak(new_node->next, new_node,
std::memory_order_release,
std::memory_order_relaxed))
; // the body of the loop is empty
}
};
I mean both head.load(std::memory_order_relaxed) and head.compare_exchange_weak(new_node->next, new_node, std::memory_order_release, std::memory_order_relaxed).
To summarize all the above, my question is essentially when do I have to care about potential reordering and when I don't?
For #1, compiler may issue the store to y before the load from x (there are no dependencies), and even if it doesn't, the load from x can be delayed at cpu/memory level.
For #2, p2 would be nonzero, but neither *p2 nor data would necessarily have a meaningful value.
For #3 there is only one act of publishing non-atomic stores made by this thread, and it is a release
You should always care about reordering, or, better, not assume any order: neither C++ nor hardware executes code top to bottom, they only respect dependencies.

Another weird issue with Garbage Collection?

OK, so here's the culprit method :
class FunctionDecl
{
// More code...
override void execute()
{
//...
writeln("Before setting... " ~ name);
Glob.functions.set(name,this);
writeln("After setting." ~ name);
//...
}
}
And here's what happens :
If omit the writeln("After setting." ~ name); line, the program crashes, just at this point
If I keep it in (using the name attribute is the key, not the writeln itself), it works just fine.
So, I suppose this is automatically garbage collected? Why is that? (A pointer to some readable reference related to GC and D would be awesome)
How can I solve that?
UPDATE :
Just tried a GC.disable() at the very beginning of my code. And... automagically, everything works again! So, that was the culprit as I had suspected. The thing is : how is this solvable without totally eliminating Garbage Collection?
UPDATE II :
Here's the full code of functionDecl.d - "unnecessary" code omitted :
//================================================
// Imports
//================================================
// ...
//================================================
// C Interface for Bison
//================================================
extern (C)
{
void* FunctionDecl_new(char* n, Expressions i, Statements s) { return cast(void*)(new FunctionDecl(to!string(n),i,s)); }
void* FunctionDecl_newFromReference(char* n, Expressions i, Expression r) { return cast(void*)(new FunctionDecl(to!string(n),i,r)); }
}
//================================================
// Functions
//================================================
class FunctionDecl : Statement
{
// .. class variables ..
this(string n, Expressions i, Statements s)
{
this(n, new Identifiers(i), s);
}
this(string n, Expressions i, Expression r)
{
this(n, new Identifiers(i), r);
}
this(string n, Identifiers i, Statements s)
{
// .. implementation ..
}
this(string n, Identifiers i, Expression r)
{
// .. implementation ..
}
// .. other unrelated methods ..
override void execute()
{
if (Glob.currentModule !is null) parentModule = Glob.currentModule.name;
Glob.functions.set(name,this);
}
}
Now as for what Glob.functions.set(name,this); does :
Glob is an instance holding global definitions
function is the class instance dealing with defined functions (it comes with a FunctionDecl[] list
set simply does that : list ~= func;
P.S. I'm 99% sure it has something to do with this one : Super-weird issue triggering "Segmentation Fault", though I'm still not sure what went wrong this time...
I think the problem is that the C function is allocating the object, but D doesn't keep a reference. If FunctionDecl_new is called back-to-back in a tight memory environment, here's what would happen:
the first one calls, creating a new object. That pointer goes into the land of C, where the D GC can't see it.
The second one goes, allocating another new object. Since memory is tight (as far as the GC pool is concerned), it tries to run a collection cycle. It finds the object from (1), but cannot find any live pointers to it, so it frees it.
The C function uses that freed object, causing the segfault.
The segfault won't always run because if there's memory to spare, the GC won't free the object when you allocate the second one, it will just use its free memory instead of collecting. That's why omitting the writeln can get rid of the crash: the ~ operator allocates, which might just put you over the edge of that memory line, triggering a collection (and, of course, running the ~ gives the gc a chance to run in the first place. If you never GC allocate, you never GC collect either - the function looks kinda like gc_allocate() { if(memory_low) gc_collect(); return GC_malloc(...); })
There's three solutions:
Immediately store a reference in the FunctionDecl_new function in a D structure, before returning:
FunctionDecl[] fdReferences;
void* FunctionDecl_new(...) {
auto n = new FunctionDecl(...);
fdReferences ~= n; // keep the reference for later so the GC can see it
return cast(void*) n;
}
Call GC.addRoot on the pointer right before you return it to C. (I don't like this solution, I think the array is better, a lot simpler.)
Use malloc to create the object to give to C:
void* FunctionDecl_new(...) {
import std.conv : emplace;
import core.stdc.stdlib : malloc;
enum size = __traits(classInstanceSize, FunctionDecl);
auto memory = malloc(size)[0 .. size]; // need to slice so we know the size
auto ref = emplace!FunctionDecl(memory, /* args to ctor */); // create the object in the malloc'd block
return memory.ptr; // give the pointer to C
}
Then, of course, you ought to free the pointer when you know it is no longer going to be used, though if you don't, it isn't really wrong.
The general rule I follow btw is any memory that crosses language barriers for storage (usage is different) ought to be allocated similarly to what that language expects: So if you pass data to C or C++, allocate it in a C fashion, e.g. with malloc. This will lead to the least surprising friction as it gets stored.
If the object is just being temporarily used, it is fine to pass a plain pointer to it, since a temp usage isn't stored or freed by the receiving function so there's less danger there. Your reference will still exist too, if nothing else, on the call stack.

identify memory leak of closure with memwatch-node

My Node.js project suffering memory leaking, I've already set variables to null in closure, I mean, I know code like this:
var a = 0;
var b = 1;
var c = 0;
example_func(c, func(){
console.log(b);
});
Will cause memory leaks, so I add some code to set these variables to null;
var a = 0;
var b = 1;
var c = 0;
example_func(c, func(){
console.log(b);
a = null;
b = null;
c = null;
});
But I still got leaks, so I try to use memwatch-node to figure out what's wrong with my code.
And the result shows that closure causing the leak, but not specified enough to target.
I've got the JSON like this
{ what: 'Closure',
'+': 12521,
size: '520.52 kb',
'-': 5118,
size_bytes: 533016 },
And I am wondering if I could get more specific details about which closure is leaking.
I've assigned name for all closures, but still not work.
You can't get more specific about which closure. memwatch gets a dump of the v8 heap and then takes differences of it and reports leaks if, after 5 successive garbage collection events, that object type count continued to grow.
Also, I believe you are confused on what closures are. The MDN page on closures gives a good description. A closure is not a variable, but a scope that enables functions to retain references and continue to work when used in a part of the code where those variable references would not otherwise be available.
If you pass functions around keep a reference to that function, it's closure could reference other closures. So, it's possible you have a single closure that could have a lot in it.
Do this: disable parts of your code until memwatch stops complaining. Then, look at that code. If you are still confused, post more details in this question.

Leaking when tried to free vector element

please help to figure this out.
I have some leaking code, and I don't know how to handle it
vector <ItemClass> items( 10 );
items[1] = ItemClass( "DVD Player", 560 );
items[5] = * new ItemClass( "Blu Ray Player", 900 );
How should I free memory for items[5] ?
I'm getting error on my attempts of freeing memory
delete &items[5];
delete [] &items[5];
I even tried something like
ItemClass * delItem = &items[5];
items[5] = item4;
delete delItem;
I'm getting "corruption of the heap" in VS2010 Ultimate
There is a strange use and mix up of storing new-allocated objects in vectors in your code. Usually you should handle lists all in the same way. Thus my examples below will be more explicit, and independent from each other which should help you understand the differences.
Use delete for objects only. See code below.
Use delete [] for "native" arrays only, not for vector or similar container classes or objects inside them.
I will not give an example for arrays though, since arrays might be more confusing.
Default example stack:
vector <ItemClass> items( 10 );
// does not need to be deleted because item is on the stack
ItemClass item("device1", "10");
items.push_back(item);
Default example with heap allocation:
vector <ItemClass*> items( 10 );
ItemClass* pItem = new ItemClass("device2", "20");
items.push_back(pItem);
// delete all items inside vector
for (int i = 0; i < items.size(); i++)
{
ItemClass* pToDelete = items[i];
delete pToDelete;
items.erase(i);
}
The following examples should be avoided and are for clarifying things up only! Use at own risk.
Storing addresses of stack variables:
vector <ItemClass*> items( 10 );
// does not need to be deleted because item is on the stack
ItemClass item("device3", "30");
items.push_back( &item ); // storing a reference to item
// No need to delete this item that points to something on the stack.
// However you might not be able to tell items apart which have been
// created on the heap or the stack, so just dont do it.
If you mix up with the example before and store references and pointers you must handle it yourself. My recommendation: Do not do this.
Storing dereferenced items:
vector <ItemClass> items( 10 );
ItemClass* pItem = new ItemClass("device4", "40");
items.push_back(*pItem);
// must be deleted because allocated on the heap
// Again you can not tell which item is allocated on stack or heap. Avoid this.
You don't call delete on objects that you don't own. You don't own items[5]. The items vector owns it.
What you need to delete is the ItemClass object that you are currently leaking, which is the one you are creating via new ItemClass(...) and then copying to items[5].
ItemClass *temp = new ItemClass("Blue Ray Player", 900);
items[5] = *temp;
delete temp;
If you want to remove items[5] from the vector, ask the vector to remove it:
items.erase(items.begin() + 5);
Note that this may be rather inefficient, because all later items in the vector have to be moved down one position, which entails calling the ItemClass assignment operator once for each moved item.
You might want to use a vector of pointers to ItemClass instead, or a vector of shared_ptrs, or a boost::ptr_vector.

Resources