Pointer to Array Element error?
collerblade via digitalmars-d-ldc
digitalmars-d-ldc at puremagic.com
Mon Jan 18 01:43:13 PST 2016
Hello guys,
Im using D llvm for my personal project, and i run into a strange
behavior. My code is:
struct Node {
string name;
...
Node[] children;
Node* search(in string nodeName) {
if(name==nodeName)
return &this;
foreach(child;children) {
auto r=child.search(nodeName);
if(r)
return r;
}
return null;
}
}
Usually first i build the tree from Node-s. Then i seach the tree
for nodes. It is pritty simple.
But today i run into a problem. The returned Node* from search
function points to invalid data. Search code:
Node* result=root.search("whatever node name");
if(result) {
writeln(result.name);
}
And this code crashes. The result.name.ptr points to some unknown
data. But the result pointer has the same value as in the search
function. This gives me headakes.
Complete code:
struct Node {
string name;
...
Node[] children;
Node* search(in string nodeName) {
if(name==nodeName) {
writeln("returned node: ",&this," name: ",name);
//0xABCDEF01 nodename
return &this;
}
foreach(child;children) {
auto r=child.search(nodeName);
if(r)
return r;
}
return null;
}
}
Node* result=root.search("whatever node name");
writeln(result); //0xABCDEF01 //same pointer as before
writeln(result.name); //crashes result.name.ptr is random
pointer, as anything else in the struct has random value
1. If i do a second search (for the same name), the result is the
same pointer value, so data is there, and it isnt moved by
anything.
2. If i search again (for the same name): the writeln() in the
search function prints the correct name, so the memory of the
struct is not been overwrited
3. If i search again (still for the same name) the
result.name.ptr is incorrect but the same as the first search
value.
4. I use unly 1 thread. And Thread.getThis() is the same
everywhere.
I dont know what the issue is here. Am i missing something?
Ty: collerblade
More information about the digitalmars-d-ldc
mailing list