Make_shared pointer is giving me issues

  • Thread starter Thread starter member 428835
  • Start date Start date
  • Tags Tags
    Issues
AI Thread Summary
The discussion centers on issues with using a raw pointer in C++ code, specifically an uninitialized pointer that leads to undefined behavior. The original code attempts to call a method on a raw pointer that has not been assigned an object, resulting in potential runtime errors. Participants clarify that a pointer should reference an instance of a class rather than the class itself, emphasizing the importance of proper initialization. A revised code example demonstrates creating an instance of the class and correctly using a pointer to call its methods. Overall, the conversation highlights the significance of understanding pointer usage and initialization in C++.
member 428835
Any idea what I'm doing wrong in the code below? It seems lines 15-16 are the problem. I thought ptr2 was a pointer. What am I missing?

C++:
#include <memory>
#include <iostream>

class c1 {
    public:
        void f1() {
            std::cout<<"im a class \n";
        }
};
int main()
{
    c1* ptr;
    ptr->f1();

    auto ptr2 = std::make_shared<c1>;
    ptr2->f1();

    return 0;
}
 
Last edited by a moderator:
  • Like
Likes pbuk
Technology news on Phys.org
ptr2 is a shared_ptr, and its use if fine.

The problem is lines 12-13.
In line 12 a "raw" pointer is declared, which is not given a value, which means that it randomly points somewhere in memory.
In line 13 that pointer is followed into "chaos and madness" as the old lint commandments describe that situation.
 
  • Like
Likes aaroman and member 428835
I like Serena said:
ptr2 is a shared_ptr, and its use if fine.

The problem is lines 12-13.
In line 12 a "raw" pointer is declared, which is not given a value, which means that it randomly points somewhere in memory.
In line 13 that pointer is followed into "chaos and madness" as the old lint commandments describe that situation.
I appreciate your reply, but this is incorrect. If you comment out 15-16 the program compiles. If you comment out 12-13 it does not.
 
Whether the program compiles does not decide whether it is fully correct. The advice you received that the raw pointer was uninitialized was correct. If you compiled with -Wall, the compiler would warn you about this. As for the compile-time error, this is invalid syntax for calling a function. Use std::make_shared<c1>().
 
  • Like
Likes aaroman, I like Serena and member 428835
Passerby said:
Whether the program compiles does not decide whether it is fully correct. The advice you received that the raw pointer was uninitialized was correct. If you compiled with -Wall, the compiler would warn you about this. As for the compile-time error, this is invalid syntax for calling a function. Use std::make_shared<c1>().
Good call on the parenthesis, but the code works and prints the desired result. Isn't the pointer pointing to the class? Because how else is the string printing?
 
Why not initialize the first pointer and see what happens?

Sometimes runtime errors occur because of earlier mistakes.
 
joshmccraney said:
Good call on the parenthesis, but the code works and prints the desired result. Isn't the pointer pointing to the class? Because how else is the string printing?
Your code neither refers to data members of c1 nor invokes virtual functions, so the implicit and uninitialized this pointer is unused. Therefore the incorrect code happened to work.
 
  • Like
Likes member 428835, Halc, I like Serena and 1 other person
joshmccraney said:
but this is incorrect. If you comment out 15-16 the program compiles. If you comment out 12-13 it does not.
Josh, have you considered taking a class? You are asking a lot of questions - A LOT - and I wonder if it would more efficient for you to take a class rather than write a few lines, hit a roadblock, ask us, argue with us for a while, get going again, and then run into your next roadblock and repeat. Most community c0lleges offer this for very little money.

Now, this argument you are having here indicates a fundamental misunderstanding. The place the error occurs is not necessarily the location of the mistake. Sometimes they can be quite separated. Consider the sentence "He are all baseball players". The error would be the "are", which doesn't match "he", but the actual mistake is "he", which should be "we".
 
  • Like
Likes aaroman, berkeman, jedishrfu and 1 other person
joshmccraney said:
Good call on the parenthesis, but the code works and prints the desired result. Isn't the pointer pointing to the class? Because how else is the string printing?
You do not want a pointer "pointing to the class", you want a pointer pointing to an object of the class. The class is just a description of what an object should be like, it is not a thing to point to. For one thing, it has no allocated space in memory. The make_shared automatically allocates and constructs an object to point to and makes the associated pointer (see https://cplusplus.com/reference/memory/make_shared/ ). Lines 15 and 16 should be ok and should print the message. Lines 12 and 13 do nothing like that. Line 12 makes a pointer that points to some random place with no meaning. It is a matter of luck as to what line 13 will do. The most likely thing is that the line 12 pointer points to a zeroed memory location and 13 does nothing. If the line 12 pointer happens to point to a protected area or to some executable code, who knows what will happen?

PS. To keep things simple, I have been a little sloppy in the details, but the general idea is correct.
 
  • Like
Likes member 428835
  • #10
Why do you even want a shared pointer? Are you trying to write multi-threaded code?
 
  • Like
Likes Vanadium 50 and FactChecker
  • #11
pbuk said:
Why do you even want a shared pointer?
The excitement!
 
  • Haha
  • Love
Likes FactChecker, pbuk and anorlunda
  • #12
Vanadium 50 said:
Josh, have you considered taking a class? You are asking a lot of questions - A LOT - and I wonder if it would more efficient for you to take a class rather than write a few lines, hit a roadblock, ask us, argue with us for a while, get going again, and then run into your next roadblock and repeat. Most community c0lleges offer this for very little money.

Now, this argument you are having here indicates a fundamental misunderstanding. The place the error occurs is not necessarily the location of the mistake. Sometimes they can be quite separated. Consider the sentence "He are all baseball players". The error would be the "are", which doesn't match "he", but the actual mistake is "he", which should be "we".
I'm not sure "argue" is accurate (though ironically that's what I'm literally doing in this post), and I think you've used the word loosely. I'm happy for you help, and the community's. Never upset when my misunderstanding is corrected, and always grateful for it (I think/hope my post history and reactions corroborate this).

Unfortunately I can't take a C++ course, but I have been googling and reading (you'd be shocked all the questions I DO have that I don't post, because usually they've been answered before). But seriously, thanks to you, and everyone, for the help. If you find it tiring or annoying, it's completely okay if there's no response. I've benefited greatly from this community, and am thankful for that.

pbuk said:
Why do you even want a shared pointer? Are you trying to write multi-threaded code?
Saw it somewhere and was trying to understand it better.

FactChecker said:
You do not want a pointer "pointing to the class", you want a pointer pointing to an object of the class. The class is just a description of what an object should be like, it is not a thing to point to. For one thing, it has no allocated space in memory. The make_shared automatically allocates and constructs an object to point to and makes the associated pointer (see https://cplusplus.com/reference/memory/make_shared/ ). Lines 15 and 16 should be ok and should print the message. Lines 12 and 13 do nothing like that. Line 12 makes a pointer that points to some random place with no meaning. It is a matter of luck as to what line 13 will do. The most likely thing is that the line 12 pointer points to a zeroed memory location and 13 does nothing. If the line 12 pointer happens to point to a protected area or to some executable code, who knows what will happen?

PS. To keep things simple, I have been a little sloppy in the details, but the general idea is correct.
This was very clear, and explains my confusion. Thanks a ton for this!
 
  • #13
Here's a slight revision of the original code that is in line with @FactChecker's comment that you shouldn't create a pointer to a class, but rather, should create an instance of the class. The code also doesn't use shared pointers. The code creates an object (instance of class c1), and then creates a pointer to that instance through which the two member functions are called.
C:
#include <memory>
#include <iostream>

class c1 {
public:
    void f1() {
        std::cout << "f1 method 1 \n";
    }

    void f2() {
        std::cout << "f2 method 2 \n";
    }
};
int main()
{
    c1 obj1;           // Create an instance of the c1 class.
    c1* ptr = &obj1;   // Create a pointer to the instance.
    ptr->f1();         // Call the function members.
    ptr->f2();    
}
 
  • Like
Likes pbuk, FactChecker and member 428835
  • #14
Mark44 said:
Here's a slight revision of the original code that is in line with @FactChecker's comment that you shouldn't create a pointer to a class, but rather, should create an instance of the class. The code also doesn't use shared pointers. The code creates an object (instance of class c1), and then creates a pointer to that instance through which the two member functions are called.
C:
#include <memory>
#include <iostream>

class c1 {
public:
    void f1() {
        std::cout << "f1 method 1 \n";
    }

    void f2() {
        std::cout << "f2 method 2 \n";
    }
};
int main()
{
    c1 obj1;           // Create an instance of the c1 class.
    c1* ptr = &obj1;   // Create a pointer to the instance.
    ptr->f1();         // Call the function members.
    ptr->f2();   
}
Makes perfect sense; thanks!
 
  • Like
Likes FactChecker
Back
Top