---
title: "withUnsafeTemporaryAllocation(byteCount:alignment:_:)"
framework: swift
role: symbol
role_heading: Function
path: "swift/withunsafetemporaryallocation(bytecount:alignment:_:)"
---

# withUnsafeTemporaryAllocation(byteCount:alignment:_:)

Provides scoped access to a raw buffer pointer with the specified byte count and alignment.

## Declaration

```swift
func withUnsafeTemporaryAllocation<R, E>(byteCount: Int, alignment: Int, _ body: (UnsafeMutableRawBufferPointer) throws(E) -> R) throws(E) -> R where E : Error, R : ~Copyable
```

## Parameters

- `byteCount`: The number of bytes to temporarily allocate. byteCount must not be negative.
- `alignment`: The alignment of the new, temporary region of allocated memory, in bytes. alignment must be a whole power of 2.
- `body`: A closure to invoke and to which the allocated buffer pointer should be passed.

## Return Value

Return Value Whatever is returned by body.

## Discussion

Discussion note: Whatever is thrown by body. This function is useful for cheaply allocating raw storage for a brief duration. Storage may be allocated on the heap or on the stack, depending on the required size and alignment. When body is called, the contents of the buffer pointer passed to it are in an unspecified, uninitialized state. body is responsible for initializing the buffer pointer before it is used and for deinitializing it before returning, but deallocation is automatic. The implementation may allocate a larger buffer pointer than is strictly necessary to contain byteCount bytes. The behavior of a program that attempts to access any such additional storage is undefined. The buffer pointer passed to body (as well as any pointers to elements in the buffer) must not escape. It will be deallocated when body returns and cannot be used afterward.

## See Also

### Memory Access

- [withUnsafePointer(to:_:)](swift/withunsafepointer(to:_:)-9fjn6.md)
- [withUnsafePointer(to:_:)](swift/withunsafepointer(to:_:)-35wrn.md)
- [withUnsafeMutablePointer(to:_:)](swift/withunsafemutablepointer(to:_:).md)
- [withUnsafeBytes(of:_:)](swift/withunsafebytes(of:_:)-5zxtl.md)
- [withUnsafeBytes(of:_:)](swift/withunsafebytes(of:_:)-5gesg.md)
- [withUnsafeMutableBytes(of:_:)](swift/withunsafemutablebytes(of:_:).md)
- [withUnsafeTemporaryAllocation(of:capacity:_:)](swift/withunsafetemporaryallocation(of:capacity:_:).md)
- [swap(_:_:)](swift/swap(_:_:).md)
- [exchange(_:with:)](swift/exchange(_:with:).md)
