Resize a memory block created by malloc. Args: target: Pointer to reallocate. size: New allocation size. Returns: Original object. Raises: InvalidSizeError: Object inside allocation is larger than attempted reallocation. AllocationErr
(target: A, size: int)
| 146 | |
| 147 | @handle |
| 148 | def realloc(target: A, size: int) -> A: |
| 149 | """Resize a memory block created by malloc. |
| 150 | |
| 151 | Args: |
| 152 | target: Pointer to reallocate. |
| 153 | size: New allocation size. |
| 154 | |
| 155 | Returns: |
| 156 | Original object. |
| 157 | |
| 158 | Raises: |
| 159 | InvalidSizeError: Object inside allocation is larger than attempted reallocation. |
| 160 | AllocationError: Raised when allocation fails, presumably due to no memory. |
| 161 | |
| 162 | Example: |
| 163 | ```py |
| 164 | ptr = malloc(1) |
| 165 | realloc(ptr, 2) |
| 166 | ``` |
| 167 | """ # noqa |
| 168 | if type(target) is StackAllocatedPointer: |
| 169 | raise TypeError("pointers to items on the stack may not be resized") |
| 170 | |
| 171 | tsize: int = sys.getsizeof(~target) |
| 172 | |
| 173 | if target.assigned and (tsize > size): |
| 174 | raise InvalidSizeError( |
| 175 | f"object inside memory is of size {tsize}, so memory cannot be set to size {size}", # noqa |
| 176 | ) |
| 177 | |
| 178 | addr = c_realloc(target.address, size) |
| 179 | |
| 180 | if not addr: |
| 181 | raise AllocationError("failed to resize memory") |
| 182 | |
| 183 | target.size = size |
| 184 | target.address = addr |
| 185 | return target |