Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ffcccc
langc
size_t resize = 1024;
size_t alignment = 1 << 12;
int *ptr;
int *ptr1;

if ((ptr = aligned_alloc(alignment , sizeof(int))) == NULL) {
  /* handleHandle error */
}

/* ... */

if ((ptr1 = realloc(ptr, resize)) == NULL) {
  /* handleHandle error */
}

The resulting program has undefined behavior because the alignment that realloc() enforces is different from that of aligned_alloc().

Implementation Details

When compiled with GCC Version version 4.1.2 and run on the x86_64 Red Hat Linux platform, the following code produces the following output:

...

This compliant solution implements an aligned realloc() function. It allocates resize bytes of new memory with the same alignment as the old memory and then moves the old memory there, consequently , freeing up the old memory.

Code Block
bgColor#ccccff
langc
size_t resize = 1024;
size_t alignment = 1 << 12;
int *ptr;
int *ptr1;

if ((ptr = aligned_alloc(alignment, sizeof(int))) == NULL) {
  /* handleHandle error */
}

/* ... */

if ((ptr1 = aligned_alloc(alignment, resize)) == NULL) {
  /* handleHandle error */
}

if ((memcpy(ptr1, ptr, sizeof(int)) == NULL) {
  /* handleHandle error */
}

free(ptr);

Risk Assessment

...

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

MEM36-C

low

probable

high

P6

L3

Bibliography

...

 

...