Download

uint8 array seemingly not clearing from memory

Edit: fixed by using std::vector<uint8>(BUFFER_SIZE) and accessing with &buffer[0] … not ideal though

So I have the following code inside a loop:



uint8 buffer[BUFFER_SIZE]; // 2MB

if (_socket->Recv(buffer, BUFFER_SIZE, read))
{
    if (read > 0)
    {
        UE_LOG(LogTemp, Error, TEXT("Actually read %i bytes"), read);
        FString message = UTF8_TO_TCHAR(buffer);
...


The value read is always correct - it matches the number of bytes coming in. However, message.Len() is problematic. Every time a message is received, message.Len() will expand to compensate for the new message size. When I UE_LOG the message, it contains data from any previous, larger messages on the end, as if it’s just replaced the first bit. For example;
[TABLE=“align: center, border: 2, cellpadding: 4, width: 700”]

		**Real Message**
		**`message`**
		**`read`**
		**Problematic `message.Len()`**
	
	
		hello
		hello
		5
		5
	
	
		triangles
		triangles
		9
		9
	
	
		hello
		hellogles
		5
		9 &lt;- *expanded beyond repair*
	
	
		a
		aellogles
		1
		9
	
	
		enormousstring
		enormousstring
		14
		14 &lt;- *expanded beyond repair*

It can’t be the case that I’m reading from freed memory as that would surely crash the engine with a memory access violation. So it indicates that the buffer is still populated in memory and part of it is overwritten each time - though not cleared beforehand. Considering the buffer is not a pointer, why does it not get cleared once it goes out of scope?

If you re-use same memory then you need manually terminate string by writing ‘\0’ at the end.



uint8 buffer[BUFFER_SIZE]; // 2MB

if (_socket->Recv(buffer, BUFFER_SIZE, read))
{
  if (read > 0)
  {
    buffer[read] = '\0';   // <- here
    UE_LOG(LogTemp, Error, TEXT("Actually read %i bytes"), read);
    FString message = UTF8_TO_TCHAR(buffer);
...