Skip to content

Instantly share code, notes, and snippets.

@Joshix-1
Last active July 11, 2024 17:39
Show Gist options
  • Select an option

  • Save Joshix-1/1597e5d36e3cfed1e41356f5e063272c to your computer and use it in GitHub Desktop.

Select an option

Save Joshix-1/1597e5d36e3cfed1e41356f5e063272c to your computer and use it in GitHub Desktop.

Revisions

  1. Joshix-1 revised this gist Jul 11, 2024. 1 changed file with 5 additions and 8 deletions.
    13 changes: 5 additions & 8 deletions segmentation_fault.cpp
    Original file line number Diff line number Diff line change
    @@ -1,24 +1,21 @@
    #include <string>
    #include <iostream>
    #include <memory>

    class Foo {
    public:
    Foo(char *chars) {
    std::cout << *data << std::endl;
    data = new std::string(chars);
    std::cout << *(data.get()) << std::endl;
    data = std::unique_ptr<std::string>(new std::string(chars));
    }

    ~Foo() {
    delete data;
    }

    std::string *data;
    std::unique_ptr<std::string> data;
    };

    int main() {
    char str[2] = {42, 0};

    Foo foo = {str};

    std::cout << "2: " << *(foo.data) << std::endl;
    std::cout << "2: " << *(foo.data.get()) << std::endl;
    }
  2. Joshix-1 created this gist Jul 11, 2024.
    24 changes: 24 additions & 0 deletions segmentation_fault.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    #include <string>
    #include <iostream>

    class Foo {
    public:
    Foo(char *chars) {
    std::cout << *data << std::endl;
    data = new std::string(chars);
    }

    ~Foo() {
    delete data;
    }

    std::string *data;
    };

    int main() {
    char str[2] = {42, 0};

    Foo foo = {str};

    std::cout << "2: " << *(foo.data) << std::endl;
    }