OSVR Framework (Internal Development Docs)  0.6-1962-g59773924
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Modules Pages
AlignedMemoryC.cpp
Go to the documentation of this file.
1 
11 // Copyright 2015 Sensics, Inc.
12 //
13 // Licensed under the Apache License, Version 2.0 (the "License");
14 // you may not use this file except in compliance with the License.
15 // You may obtain a copy of the License at
16 //
17 // http://www.apache.org/licenses/LICENSE-2.0
18 //
19 // Unless required by applicable law or agreed to in writing, software
20 // distributed under the License is distributed on an "AS IS" BASIS,
21 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 // See the License for the specific language governing permissions and
23 // limitations under the License.
24 
25 // Internal Includes
28 
29 // Library/third-party includes
30 // - none
31 
32 // Standard includes
33 #include <stdlib.h>
34 #include <cassert>
35 
36 void *osvrAlignedAlloc(size_t bytes, size_t alignment) {
37  // Allocate a memory buffer with enough space to store a pointer to the
38  // original buffer.
39  auto space = bytes + alignment;
40  void *buffer = malloc(space + sizeof(void *));
41  if (!buffer) {
42  return nullptr;
43  }
44 
45  // Reserve the first byte for our buffer pointer for later freeing.
46  void *alignBase = (void **)buffer + 1;
47 
48  // After this call the 'alignBase' pointer will be aligned to a boundary.
49  // If there is not enough space to align the pointer, it stays
50  // unaligned, and nullptr is returned insted of the updated alignBase.
51  void *ret = osvr::align(alignment, bytes, alignBase, space);
52 
53  if (space < bytes || !ret) {
54  free(buffer);
55  return nullptr;
56  }
57 
58  // Store the buffer pointer for the free call.
59  ((void **)ret)[-1] = buffer;
60 
61  return ret;
62 }
63 
64 void osvrAlignedFree(void *p) {
65  // Null-pointer should be a no-op.
66  if (p) {
67  free(((void **)p)[-1]);
68  }
69 }
void * osvrAlignedAlloc(size_t bytes, size_t alignment)
Aligned allocation function, gives a pointer to a block of memory aligned to a memory boundary...
void osvrAlignedFree(void *p)
Aligned deallocation function, uses the pointer to the original memory block to deallocate it...
Header wrapping std::align or a backported version - whichever we have is imported into the osvr name...