Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Wow. What you're trying to do is a complete abuse of C++, would be totally compiler dependent if it worked, and would surely land you in TheDailyWTF some day.</p> <p>The reason you're getting a segfault is probably because your operator= is reallocating the object to a different address, but you're not updating the myString pointer in main. I hesitate to even call it an object at this point, since no constructor was ever called.</p> <p>I think what you're trying to do is make pString a smarter pointer to a string, but you're going about it all wrong. Let me take a crack at it.</p> <pre><code>#include &lt;iostream&gt; using namespace std; class pString { public: char * c; pString &amp; operator=(const char *); const char * c_str(); }; pString &amp; pString::operator=(const char * buff) { cout &lt;&lt; "Address of this: " &lt;&lt; (uint32_t) this &lt;&lt; endl; cout &lt;&lt; "Address of this-&gt;c: " &lt;&lt; (uint32_t) this-&gt;c &lt;&lt; endl; c = (char *) malloc(strlen(buff)+1); memcpy(c, buff, strlen(buff)); *(c+strlen(buff)) = '\0'; return *this; }; const char * pString::c_str() { return c; } int main() { pString myString; myString = "testing"; cout &lt;&lt; "'" &lt;&lt; myString.c_str() &lt;&lt; "'"; </code></pre> <p>}</p> <p>Now I wouldn't use malloc but new/delete instead, but I left this as close to your original as possible.</p> <p>You <b>might think</b> you are wasting the space of a pointer in your class, but you aren't - you're trading it for the pointer you previously kept in main. I hope this example makes it clear - the variables are the same size, and the amount of additional memory allocated by malloc/realloc is the same as well.</p> <pre><code>pString myString; char * charString; assert(sizeof(myString) == sizeof(charString)); </code></pre> <p>P.S. I should point out that this code still needs a lot of work, it's full of holes. You need a constructor to initialize the pointer, and a destructor to free it when it's done, just for starters. You can do your own implementation of operator+, too.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload