"Connection reset by peer" when reading to heap memory with TcpStream

This code here works without any problem, fine:

use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;

fn main() {
    let listener = TcpListener::bind("").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();

fn handle_connection(mut stream: TcpStream) {
    let mut buffer = [0; 512];
    stream.read(&mut buffer).unwrap();
    println!("{}", String::from_utf8_lossy(&buffer[..]));

This is written with using stack memory that has a fixed size of allocated memory, but I want to allocate
dynamic memory (perhaps more memory) for my program. So basically, I replaced let mut buffer = [0; 512]; with let mut buffer = Vec::new(); But it resets the connection when it does read.

If you want to create a simple reproducible example in your machine, execute nc 9999 command and send anything to the server.

using a Vec like this, it's initial length is 0, so that's how many bytes you will read. You should use read_to_end for unbounded memory or use a bigger buffer size like let mut buffer = vec![0;8196];

1 Like