News:

Simutrans Wiki Manual
The official on-line manual for Simutrans. Read and contribute.

Question regarding freelist.cc

Started by knightly, May 19, 2009, 09:44:08 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

knightly

Hi,

I have been reading the code for freelist.cc, but there is something that I cannot get through, probably because I missed something.

In the code :

Quote
   list = &(all_lists[(size+3)/4]);

Memory fragments of 4 different sizes may share the same slot in all_lists[]. For example, sizes of 21, 22, 23 & 24 all go to the same slot of all_lists[6].

Below is the code for allocating new memory in case a slot is empty :

Quote
   if(*list==NULL) {
      int num_elements = 32764/(int)size;
      char* p = (char*)xmalloc(num_elements * size + sizeof(p));
      // put the memory into the chunklist for free it
      nodelist_node_t *chunk = (nodelist_node_t *)p;
      chunk->next = chunk_list;
      chunk_list = chunk;
      p += sizeof(p);
      // then enter nodes into nodelist
      for( int i=0;  i<num_elements;  i++ ) {
         nodelist_node_t *tmp = (nodelist_node_t *)(p+i*size);
         tmp->next = *list;
         *list = tmp;
      }
   }

Even if size is not a multiple of 4, it is not adjusted upward to the next multiple of 4 when calculating the size of new memory to be allocated.

I suspect there will be a problem in the following scenario :

Assuming all_lists[6] is currently empty (i.e. == NULL), and a piece of memory is needed with a size of 21. Total size of new memory allocated will be (num_elements * 21 + sizeof(p)), and each piece of memory (node) will have a size of 21. If later a piece of memory of size 24 is requested, freelist will go to all_lists[6] for a node and return its pointer. However, that node has a size of 21, so the variable that needs 24 bytes will overwrite some bytes in the next node.

Probably this will not occur, and it's very likely that I have overlooked something. I wonder if anyone can kindly shed light on this. Many thanks in advance!

prissi

I think this is a bug which probably rarely happens since all structures are usually multiples of 4.

knightly

#2
Thanks for your reply, prissi. That cleared my doubts. :)

Edit :  Just in case this bug will be fixed, please also check the size of any memory piece that is put back, to make sure that recycled memory fragments are of proper size (i.e. multiples of 4).

jamespetts

I have noticed occasional crashes that appear to be connected to freelist - when closing certain saved games, for example. Perhaps it is related to the bug that Knightly has just found?
Download Simutrans-Extended.

Want to help with development? See here for things to do for coding, and here for information on how to make graphics/objects.

Follow Simutrans-Extended on Facebook.