Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor edits

If ptr was allocated with an alignment returned from aligned_alloc() and if realloc() reallocates memory with a different alignment then, the behavior is undefined.

This rule is specifically for C1X standards.

Non- Compliant Code

only applies to compilers that conform to the (emerging) C1X standard add ref.

Noncompliant Code Example

This noncompliant code example aligns ptr to a 4096 byte boundary whereas This non-compliant example shows that ptr is aligned to an alignment of 4096 bytes where as the realloc() function aligns the memory to a different alignment .
(Assuming assuming that the sizeof(double) = 8 and sizeof(float) = 4.)

Code Block
bgColor#ffcccc
size_t size = 16;
size_t alignment = 1<<12;
float *ptr;
double *ptr1;

ptr = aligned_alloc(align , size);
ptr1 = realloc(ptr, size);

The realloc function resulting program has an undefined behavior as the alignment that realloc() enforces is different from aligned_alloc() function's alignment.

...

This compliant example checks that aligned_alloc() has the same alignment as the alignment realloc() function enforces on the memory pointed to by ptr.
(Assuming again assuming that the sizeof(double) = 8 and sizeof(float) = 4).)

Code Block
bgColor#ccccff
size_t size = 16;
size_t alignment = 1<<12;
float *ptr;
double *ptr1;

ptr = aligned_alloc(align , size);

if(align == alignof(ptr1)) {
  ptr1 = realloc(ptr, size);
}

Implementation Details

unmigrated-wiki-markup
Wiki Markup
The non-compliantnoncompliant examplecodexample produces the following (unexpected) output on the x86_64-redhat-linux platform that was compiled with gcc version 4.1.2.
({{ptr\[0\]}} is initialized to 12.5 and {{ptr\[1\]}} is initialized to 25.5)

Code Block

ptr

...

[0

...

] (0x2b7000000000) = 12.500000
ptr

...

[1

...

] (0x2b7000000004) = 25.500000
ptr1

...

[0

...

] (0x2b7000000000) = 12.500000
ptr1

...

[1

...

] (0x2b7000000008) = 0.000000

Risk Assessment

Improper alignment could lead to accessing arbitrary memory locations and write into it.

...