Make_shared pointer is giving me issues

  • Thread starter member 428835
  • Start date
  • Tags
    Issues
I've gone through). So I'm stuck asking for help.In summary, the conversation discusses an issue with code in lines 12-13, where a raw pointer is declared but not given a value, causing it to randomly point to a memory location. The suggestion is to use std::make_shared to allocate and construct an object to point to. The use of a shared pointer is questioned, and the conversation also touches on the benefits of taking a class to learn C++.
  • #1
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
  • #2
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
  • #3
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.
 
  • #4
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
  • #5
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?
 
  • #6
Why not initialize the first pointer and see what happens?

Sometimes runtime errors occur because of earlier mistakes.
 
  • #7
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
  • #8
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
  • #9
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

FAQ: Make_shared pointer is giving me issues

1. Why is my make_shared pointer not working?

There could be several reasons why your make_shared pointer is not working. Some common issues include passing in the wrong arguments, attempting to access a null pointer, or trying to access a deleted object. It's important to carefully check your code and make sure all arguments are correct and that the pointer is valid before attempting to use it.

2. How do I fix issues with my make_shared pointer?

The first step in fixing issues with your make_shared pointer is to carefully review your code and identify any potential errors. It may also be helpful to use debugging tools to track the flow of your code and identify where the issue is occurring. Additionally, make sure you are properly managing memory and not attempting to access deleted objects.

3. Is make_shared pointer safe to use?

Overall, make_shared pointer is considered a safe and efficient way to manage memory in C++. However, as with any programming tool, it is important to use it correctly and carefully review your code for potential errors. Make sure to properly initialize your pointer and avoid common pitfalls such as passing in incorrect arguments or attempting to access a null pointer.

4. Can make_shared pointer cause memory leaks?

No, make_shared pointer is designed to help prevent memory leaks by automatically managing the lifetime of the allocated object. However, it is still possible to create memory leaks if the pointer is not used correctly. It is important to carefully manage the lifetime of the object and avoid creating multiple shared pointers to the same object.

5. Are there any alternatives to using make_shared pointer?

Yes, there are other ways to manage memory in C++, such as using raw pointers or unique pointers. However, make_shared pointer is generally considered a safer and more efficient option. It also offers the benefit of automatically managing the lifetime of the allocated object, which can help prevent memory leaks. Ultimately, the best option will depend on the specific needs of your program.

Similar threads

Replies
22
Views
2K
Replies
1
Views
1K
Replies
118
Views
7K
Replies
8
Views
2K
Replies
19
Views
3K
Replies
13
Views
1K
Back
Top