Search code examples
c++performancecpu-speed

deleting 2D Linked List array, How to?


I have function like this for delete my 2 dimensional struct, but it is not too fast, i guess there is a much faster way to do this(Like memset or something), any idea would be appreciated;)

 void freeAlllistNode(LISTNODEPTR *sPtr[][10])
{   LISTNODEPTR temp;
for (char i = 0; i<19; i++){
    for (char di = 0; di<10; di++){
        while (sPtr[i][di] != NULL){
            temp = *(sPtr[i] + di);
            *(sPtr[i] + di) = temp->next;
            free(temp);
        }
    }
  }
}

And this is my struct definition, in case if it's necessary

typedef struct listNode{
char* val ;
struct listNode *next;
}LISTNODE;
using LISTNODEPTR = LISTNODE*;

Solution

  • No. memset is never a replacement for malloc/free, in any circumstance. They do completely different things. A proposal that memset could somehow be a replacement for malloc/free is a fundamental misunderstanding of how dynamic memory, and dynamic scope allocation works.

    The only thing that could even remotely implement something like that would be standard C++ library containers with a custom allocation class. That is, std::list, std::vector, and others, and none of this manual link list implementation.

    Standard C++ library containers take an optional template parameter that specify a custom allocator class. A custom allocator class would have to be written that manages dynamic memory allocation for the container, something along the lines of allocating large chunks of memory, and then doling them out, piecewise, for each value placed into the container. Then, when the container gets destroyed, all allocated memory could be disposed of in a few, short, deletes.

    It would, of course, be possible to also implement this approach with a manual link list implementation. But it's a lot of work anyway, and as long as all that work has to be done, why waste any more time with a manual link list, just use std::list.