Welcome, Guest. Please login or register.

Author Topic: Help bughunt this (a good pointer exercise too)...  (Read 2125 times)

Description:

0 Members and 1 Guest are viewing this topic.

Offline Piru

  • \' union select name,pwd--
  • Hero Member
  • *****
  • Join Date: Aug 2002
  • Posts: 6946
    • Show all replies
    • http://www.iki.fi/sintonen/
Re: Help bughunt this (a good pointer exercise too)...
« on: May 28, 2005, 10:08:10 PM »
Few things I noticed after 5 mins:

- the style is horrible. the source code is totally unreadable unless if you reformat it.

- you can't FreeMem partial chunks of allocated memory. It might work with certain systems, and fail with others.

- memory allocation and deallocation work with granularity of 8 bytes. if you freemem ptr + 1, you actually end up freeing ptr + 8.

- the memory not freed is taken permanently from the system (until next reboot).

- the test loop (probably) uses wrong variable:
Code: [Select]
for (TestCounter = 0; IndexCounter <= 255; IndexCounter++)
should be:
Code: [Select]
for (TestCounter = 0; TestCounter <= 255; TestCounter++)
 

Offline Piru

  • \' union select name,pwd--
  • Hero Member
  • *****
  • Join Date: Aug 2002
  • Posts: 6946
    • Show all replies
    • http://www.iki.fi/sintonen/
Re: Help bughunt this (a good pointer exercise too)...
« Reply #1 on: May 28, 2005, 10:44:32 PM »
Yet, while I completely fail to see any purpose for creating such an array, here's what I came up with:

Code: [Select]

#include <exec/types.h>
#include <exec/memory.h>
#include <stdio.h>

#include <proto/exec.h>

int main (int argc, char **argv)
{
  struct entry
  {
    UBYTE b[8];
  } *array;

  /* NOTE: Only the array of the last entry will actually take 9 bytes
   * (since it has all bits set: 7 6 5 4 3 2 1 0. Thus only the last
   * entry needs to have array of 9 bytes. Thus + 1.
   */
  array = AllocMem(sizeof(*array) * 256 + 1, MEMF_ANY);
  if (array)
  {
    int i;

    for (i = 0; i < 256; i++)
    {
      int n, cnt = 0;

      for (n = 8; n >= 0; n--)
      {
        if (i & (1 << n))
        {
          array[i].b[cnt++] = n + 1;
        }
      }
      array[i].b[cnt] = 0;
    }

    /* TEST IT ! */
    for (i = 0; i < 256; i++)
    {
      UBYTE *p = array[i].b;

      printf(&quot;%u: &quot;, i);
      while (*p)
      {
        printf(&quot;%u &quot;, *p++);
      }
      printf(&quot;\n&quot;);
    }

    FreeMem(array, sizeof(*array) * 256 + 1);
  }
  else
  {
    printf(&quot;No more memory !!\n&quot;);
  }

  return 0;
}


I took the liberty of changing the array type for simpler and more efficient code.