esp8266 / esp8266/Arduino

String clear() does not free memory, only set length(0)

Open
#8,485 22 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
16.7k
Forks
13.1k
PR merge metrics
No merged PRs in 30d

Description

### Basic Infos

- [x] This issue complies with the [issue POLICY doc](https://github.com/esp8266/Arduino/blob/master/POLICY.md).
- [x] I have read the documentation at [readthedocs](https://arduino-esp8266.readthedocs.io/en/latest) and the issue is not addressed there.
- [x] I have tested that the issue is present in current master branch (aka latest git).
- [x] I have searched the issue tracker for a similar issue.
- [ ] If there is a stack dump, I have decoded it.
- [ ] I have filled out all fields below.

#### Platform

- Hardware: [ESP-12|ESP-01|ESP-07|ESP8285 device|other]
- Core Version: [latest git]

### Problem Description

The String::clear() function does only set the length to 0, it does not free the memory.
The same for assigning an empty string, as this only checks if the reserved capacity is enough.

This means it is quite tricky when clearing a string that's no longer needed.
For example a buffer I'm using, which is an array of String.

The only way to really free the memory is by assigning a new string which will then be copied using the move operator, like this:

```c++
Message[read_idx] = String();
```

It does not really make sense to only set the length of the string to 0, as that's not what `clear()` suggests.

Or at least have some function like `free()` to actually free the allocated memory.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.