Can't allocate 1 MB, but can alloc 2?

Discuss the development of new homebrew software, tools and libraries.

Moderators: cheriff, TyRaNiD

Post Reply
svxs
Posts: 15
Joined: Fri Jun 19, 2009 10:03 am

Can't allocate 1 MB, but can alloc 2?

Post by svxs »

It's the weirdest problem.

Code: Select all

  #define ALIGNED(nBytes) __attribute__((aligned(nBytes)))

  // types:
  typedef unsigned char byte_t;
  // uint32_t, etc, are from <stdint.h> &#40;this is c99 code&#41;

  struct dim2d
  &#123;
    uint32_t y;                                                    /* Height */
    uint32_t x;                                                     /* Width */
  &#125;;

  struct mipmap
  &#123;
    struct dim2d xy;                                    /* Mipmap dimensions */
    byte_t ALIGNED &#40;16&#41; data&#91;&#93;;                                /* Pixel data */
  &#125;;

  ...

  pImage->p_mipmaps&#91;i&#93; = malloc &#40;sizeof &#40;struct mipmap&#41; + size&#41;;
  if &#40; pImage->p_mipmaps&#91;i&#93; == NULL &#41;
    &#123;
      // ignore this for now
      // for &#40; uint32_t b = 0; b < i; b++ &#41;
      //  free &#40;pImage->p_mipmaps&#91;b&#93;&#41;;

      pspDebugScreenPrintf &#40;"Couldn't allocate %i bytes.\n"
                 , sizeof &#40;struct mipmap&#41; + size&#41;;

      for &#40; uint32_t i = 1; i < 5; i++ &#41;
      &#123;
        byte_t *p_x = malloc &#40;i * 1024 * 1024&#41;;
        if &#40; p_x == NULL &#41;
          pspDebugScreenPrintf &#40;"Couldn't allocate %i bytes.\n"
                     , i * 1024 * 1024&#41;;
        else
        &#123;
          pspDebugScreenPrintf &#40;"COULD allocate %i bytes.\n"
                     , i * 1024 * 1024&#41;;
          free &#40;p_x&#41;;
        &#125;
      &#125;

      return DDS_OUT_OF_MEMORY;
    &#125;

  ...
will display:

Code: Select all

  Couldn't allocate 8208 bytes.
  Couldn't allocate 1048576 bytes.
  COULD allocate 2091752 bytes.
  COULD allocate 3145728 bytes.
  COULD allocate 4194304 bytes.
It only happens after I've already done a lot of malloc() and free()'s. Otherwise, it works fine. It also works fine if I change it up weirdly:

Code: Select all

  ...
  struct mipmap
  &#123;
    struct dim2d xy;                                   /* Mipmap dimensions */
    // Got rid of ALIGNED &#40;16&#41; from this&#58;
    byte_t data&#91;&#93;;                                             /* Pixel data */
  &#125;;
  ...
  // Use memalign, align to 64 &#40;16 still breaks&#41;&#58;
  pImage->p_mipmaps&#91;i&#93; = memalign &#40;64, sizeof &#40;struct mipmap&#41; + size&#41;;
Any ideas what's going wrong?
svxs
Posts: 15
Joined: Fri Jun 19, 2009 10:03 am

Post by svxs »

Turned out to be some heap corruption from an off-by-one error in another function that was being called repeatedly before this chunk of code. Works fine after I found that.
Post Reply