Reates a temporary which is freed while still in use

Hi
I have the dreaded creates temporary which is freed error . I tried doing the clone but that does not solve the error. I also looked at the other posts in the forum on the same topic .
This is inside a match fragment.The code is below and the error is also attached

let mut client_ip_address = "";
if dns.additionals.len() != 0 {
    let additionals = dns.additionals;
    match &additionals[0] {
        dns_message_parser::rr::RR::OPT(m) => {
            if m.edns_options.len() > 0 {
                let edns_options = &m.edns_options;
                let edns_options = match &edns_options[0] {
                dns_message_parser::rr::edns::EDNSOption::ECS(m1) => {
                                   
                    m1
                }

                _ =>{
                        eprintln!("Found a non EDNS message ");
                        return Err("Error ".into());
                }
            };
      // ERROR
                            
            let x1 = &edns_options.get_address().to_string().clone();
            client_ip_address = x1;
        }
    }
    _ => {
            eprintln!("Found a non OPT message ");
            return Err("Error ".into());
         }
    }
}
println!("{:}",client_ip_address);
error[E0716]: temporary value dropped while borrowed
    
    |
    |                             let x1 = &edns_options.get_address().to_string().clone();
    |                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ creates a temporary which is freed while still in use
    |                             client_ip_address = x1;
    |                         }
    |                         - temporary value is freed at the end of this statement
...
    |                     client_ip_address,
    |                     ----------------- borrow later used here
    |
    = note: consider using a `let` binding to create a longer lived value

The problem is that edns_options.get_address().to_string() (with or without .clone()) is producing a String that isn't being stored anywhere, so it gets freed at the end of the statement. You then take a reference to it with &, which can't live longer than the temporary. The easiest fix is to store the String instead of a reference:

let mut client_ip_address: String = String::new();
// ...
client_ip_address = edns_options.get_address().to_string();

Depending on how dns_message_parser is built, this might also work, as it doesn't create a temporary String; I haven't checked:

let mut client_ip_address = "";
// ...
client_ip_address = edns_options.get_address();

This worked very well. Thanks .The 2nd option did not work since it is returning an Enum

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.