Hello!
I'm making a function that generates a random name (only once). The names are originally stored in a linked list (doubly circular)
1)I copy the names in an array of strings (in order to generate a random index each time, 2) look for the string( with the given index)in the linked list and if existing, will call a delete function to delete it, if not found it will be called again, after generating many strings, my program crashes.
here is the function:
OP: could you please re-read your post and see if it makes full sense to you and whether some bits of it might do with an edit for greater clarity? Thanks
Bloc* searchKname(Bloc* root, string kName)
{
for(Bloc*it = root->nxt; it!=root; it=it->nxt) {
if(it->name==kName) return it;
}
}
void deleteKname(Bloc*&root, Bloc*p)
{
if(p->prev!=root) {p->prev->nxt = p->nxt;}
else {root=p->nxt;}
if(p->nxt!=root) {p->nxt->prev = p->prev;}
delete(p);
}
// int the main
for(Bloc* it = root->nxt; it!=root ; it= it->nxt ){
randName=generate(root);
//tmp is a pointer to hold the returned block that contains the randName
tmp=searchKname(root, randName);
//deletedList is for saving the deleted names from the original one
deletedList=createList();
//addAfterRoot to keep the order of deleted list elements
addAfterRoot(deletedList, randName);
//sending the original list (root) and the element to delete (tmp)
deleteKname(racine,tmp);
}
It is impossible to say if line 19 is safe as we don't know of any invariants that hold true for your linked list. If it is possible that p->prev is null and that root is not null, then line 19 will result in dereferencing a null pointer.
The same issue occurs on line 22 with p->next.
Also, delete is not a function. delete p; is equivalent to delete (p);.