c++ - How to copy a non null terminated string to dynamic memory -


first off, not duplicate. question how dynamic memory. reason distinct because delete[] hanging.

so, here's have:

class packetstrret {     public:     packetstrret(char p_data[], int p_len) : len(p_len) {         data = new char[p_len];         memcpy(data, p_data, p_len * sizeof(char));     }      ~packetstrret() {          delete[] data;          data = nullptr;     }      char* data;     int len; }; 

and yes, i'm aware code not using best practices. i'll clean later.

the problem i'm having in dtor. delete hanging forever. data being passed in ctor not dynamic memory, need make dynamic things don't go out of scope. p_len holds correct amount of data, there's no problem there.

from i've read, memcpy seems culprit here. how copy string not null-terminated dynamic memory, , still able delete later?

thanks.

the problem not delete, comes before , ok if there didn't occur problems.

class packetstrret {     // use raii     std::unique_ptr<char> data; // own data , destroy it.     // parent class movable, use shared_ptr if can't live that.     int len;      public:     packetstrret(         // <red alert>         char p_data[], int p_len // user can lie us.         // </red alert>         ) try : // function try block, se 1)           len(p_len), data(new char[p_len]) {         memcpy(data, p_data.get(), p_len * sizeof(char));     } catch(const std::exception& e) {       std::cerr << "arg=" << arg << " failed: " << e.what() << '\n';     }      ~packetstrret() {          // unique_ptr takes care of memory management , garbage collection.     }        // access functions }; 

now possible errors make blow code up.

you have copied object, making 2 owning raw pointers same data. blow @ delete, coudl use memory-sanitizer / valgrind confirm happens. use smart pointers save trouble, unique pointer should cause compiler error if tried copy, unless memcpy entire structure ignoring copy/assignment constructors.

you give wrong len constructor, source of data , len? valgrind / memory-sanitizer can save you.

the memory corruption happen in totally different place. valgrind / memory-sanitizer can save you.

in case valgrind mem-san much, can try make check double delete, if make counter in c'tor , d'tor , if ever goes negative have error.

in class @ least missing copy constructor. check on rule of 3, 5, 7 , 0 (zero) find out how many need.

1) http://en.cppreference.com/w/cpp/language/function-try-block


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -