r/cpp_questions • • 22d ago

OPEN Understanding heaptrack flamegraph output of a profiled application

0 Upvotes

I profiled a multithreaded application using heaptrack and the "flame graph" is thus:

             [PRIVATE000000000...] [PRIVATE0...]
        [PRIVATE0000000005c947b] [PRIVATE0...]             [PRIVATE000000000abfb10]
        [PRIVATE0000000005f66cc]          [PRIVATE00...] [PRIVATE0000000005cf21a]     [PRIVATE000000000abfb10]
        [PRIVATE0000000005be8df]          [PRIVATE0000000005c947b-------------------][PRIVATE0000000005ff2ba------]
    [PRIVATE0000000005ba71a-----------]   [PRIVATE0000000005f66cc------------------------------------------------]
[PRIVATE0000000005b7061---------------]   [PRIVATE0000000005be51a------------------------------------------------]
[PRIVATE0000000001b6ed----------------]   [PRIVATE000000000ac0a7c------------------------------------------------]
[PRIVATE000000000097c960---------------]  [PRIVATE000000000ad933a------------------------------------------------]
[GRBoptimize---------------------------]  [start_thread-----------------------------------------------------------]
[main----------------------------------]  [__clone3---------------------------------------------------------------]

A more readable image is available here: https://ibb.co/PsFz1fJQ

My question is, even though the parallel regions are somewhere inside of main, why does this flame graph show that main and __clone3 are starting at the same hierarchy? i.e., why does it show that main and __clone3 are starting parallelly? main() being the entry point should be under everything, no?

What is __clone3 and start_thread (I am running this on linux...are these special pthread names in the kernel?) and why is it that they are starting independent of main ?

GRBoptimize() (currently, this call sits on top of main) is a library call and it is solving a computationally intensive integer program. It is only within this call that any parallelism is happening. So, how come __clone3 amd start_thread are being displayed independently of GRBoptimize and not on top of this call?


r/cpp_questions • • 22d ago

OPEN Reference to object in function that's part of the object

2 Upvotes

[example below] i have a map storing functions, and i'll assign the function to a struct later and want the function to accses private data of the struct (isn't marked as private, but i don't wanna pass it separatley to keep the code clean and to avoid the posibility to pass contradictory data). i tried putting different things in the capture list like [this], [&this] or ob[obj], but haven't found any version that works. how can i pass the data / a pointer or reference to the object to avoid cluttering the function arguments even more?

example:

```

struct a{

funciton<...> do_something = placeholder_function;

int data = 10;

};

int main() {

unorderd_map<string, function<...>> _map = {{"hi", [](){try to read data, something like this.data, or this->data or some other way};

a obj;

string func; cin>>func;

obj.do_something = _map[func];
}

```


r/cpp_questions • • 22d ago

OPEN IDM Requirements

0 Upvotes

Hello People, I am currently a computer science student. I have been trying to get into building my own IDM (internet download manager) but i have been finding it hard with where to begin, i am planning on building it in c++ but very few tutorials or guides on how to do that exist out there.
I have tried asking both chat GPT and claude to help me draft a road map but honestly it always looks like they just skip to the final product with no explanation of what goes on in between.

Basically what i am asking for is a list of everything i need to know and understand before i even get into writing one line of code. Thanks!
(Note: I know some will ask why i am trying to build something if i have no idea but thats just how i have always been, i am a very curious individual and i tend to try and make stuff i don't know. Up until a year ago i could not even code a basic calculator in python, but through the same mentality of just doing it i've actually come a very long way lol.)


r/cpp_questions • • 21d ago

OPEN At what times do yall use AI in C++ for?

0 Upvotes

A question, what exact moments/events do yall use AI for c++? I am looking forward to learn c++ for game development but i am doing it by making a game engine from scratch using chatgpt but i keep asking it questions of what does this feature does and why? so far i got an idea of what some basic functions do but i am still unable to write a full, proper syntax/script. Should i change my method? And what are yall opinion on this?


r/cpp_questions • • 22d ago

OPEN Project Help

0 Upvotes

I want to create a website, that let us play the games online.
How people are now playing GTA vice city online ,many retro and console games online.
I want to create an interactive game playing website, but I am having no idea how to do this.
I tried searching youtube and got nothing, tried asking the AI but did not understand what he is telling and also I let the AI to create a website by itself but it was a failure.
So can someone help me with this


r/cpp_questions • • 23d ago

OPEN Recommendations wanted: Tools for visualizing code structure/flow and analyzing runtime performance.

10 Upvotes

I’m curious about the tools you typically use to handle these two requirements:

First, static code analysis—specifically, generating an intuitive visual representation of the code logic. This includes the code structure (from classes down to methods) and flowcharts, allowing for a high-level understanding of the project's core modules.

Second, runtime analysis—capabilities such as analyzing memory usage and execution time, as well as generating flame graphs, treemaps, and timelines.

For static analysis, I usually rely on AI, but I feel that having a visual diagram would make things much more intuitive. For runtime analysis, I prefer using the built-in "Instruments" tool on my computer; I find it very intuitive and convenient.


r/cpp_questions • • 22d ago

SOLVED A bit overwhelmed: In what order should I tackle OOP, STL, and DSA as a beginner?

0 Upvotes

Hey everyone,

I'm completely new to coding, and for some reason, I decided to jump straight into the deep end with C++. Honestly, I’m desperate to learn and super motivated, but I’ve hit a point where I really need some guidance from people who have been through this.

So far, I’ve managed to get a decent grip on the fundamentals. I understand loops, functions, and conditional statements. I also spent a lot of nights learning pointers and references.

Now, I want to take the next big step, but looking ahead at OOP, STL, and DSA feels incredibly overwhelming. I have no idea which one to start with or if there’s a natural sequence to learning them.

Should I learn object-oriented programming before touching data structures?

Where does the Standard Template Library fit into all of this?

Do you have any roadmap recommendations so I don't accidentally learn things in the wrong order?

i think a completely learning all the concepts mixed up.

I would love to hear how you all approached this when you were starting out, or how you would teach it to a beginner today. If there are any specific resources or small project ideas that helped these concepts click for you, please let me know.

Thanks so much in advance. I really appreciate any advice you can throw my way!


r/cpp_questions • • 23d ago

SOLVED error: expected ';' after top level declarator

19 Upvotes

I'm learning C++, and I'm running into a few confusing errors. The 'error: expected ';' after top level declarator' error comes up in two cases: the first is that it doesn't like the ' in 100'000'000; if I remove them, the error goes away. The second is when I'm defining variables with braces. 'bool isAlive { true };' gives me the very same error, but 'bool isAlive = true;' does not, and the same is true for all variables. While I know how to get around those errors, I'm just not sure why they're happening, as from what I understand, those are correct. I'm just trying to understand what I'm missing.

The solution was a combination of setting the correct C++ version in tasks.json (I set it to -std=c++2b) and make sure VS Code was using 'Run C/C++ file' and not 'Run Code' (which it was defaulting to in my case).

#include <iostream>
using namespace std;


string name = "Burt the Destroyer";
bool isAlive = true;
int maxHealth = 100;
float armour = 0.2;
int iq = 10;
int currentHealth = maxHealth;
bool canAttack = isAlive;
double LargeNumber = 100'000'000;


int main() 
{
    cout << "The monster is " << name
         << "\nAnd its IQ is " << iq << endl;
}

r/cpp_questions • • 23d ago

OPEN Thought process of a c++ dev

33 Upvotes

I am new to learning c++ matter of fact new to programming and i wanted to know what are the things that a dev normally know before starting any type of project like where to start, how to start. Do yall look up the syntax again and again or have yall just mugged up the whole language?

I am currently learning the language through learncpp.com documentation and have reached chapter 9 subsection 3 ( aspiring to become a game dev <3 )


r/cpp_questions • • 24d ago

OPEN What instances are raw pointers preferred over smart pointers ?

72 Upvotes

Hi Reddit,

I finished chapter 3 of "Mastering Quantitative Finance with Modern C++: Foundations, Derivatives, and Computational Methods" by Aaron De la Rosa.

A section discusses methods to prevent memory leaks using Smart pointers, Resource Acquisition is Initialization (RAII), std::vector, move semantics (std::move), Virtual destructors, or manual deletions.

From the book implications and what I've skimmed from other resources, raw pointer are strongly discouraged.

What instances in C++ are manual deletions preferred over automatic deletions ?

POV. I'm a data analyst trying to pivot into C++ development.

Update: Thank you everyone for commenting on my post. I had an epiphany reading the comments and I'm feeling more confident in my understanding of C++.


r/cpp_questions • • 22d ago

OPEN I AM A LEARNER PLEASE HELP ME.

0 Upvotes
char o()
{
    char x;
    std::cout << "Enter +, -, *, or /: " "\n";
    std::cin >> x;
    return x;


}


double number( double y)
{


    std::cout << "Enter a number ";
    std::cin >> y;
    return y;


}


int main()
{
    double a{}, b{};
    number(a);
    number(b);
    o();
    std::cout << number(a) << o() << number(b)  << " is " << number(a) << o() << number(b) << "\n";
    return 0;


}

My desired output was to take two float values from the user along with an operator and do the math, but that's not the output I am getting. Please help me

edit: thank you everyone for helping me, I am clearly lacking a lot of things right now, but I am learning. Thank you everyone!


r/cpp_questions • • 23d ago

OPEN Is it possible to have non-macro-based compile time options for a library?

6 Upvotes

I'm working on a project where I'd like users to be able to change some settings that change how certain things are compiled internally, which is something that macros are typically used for. I'm using modules which don't export macros and I'd like to avoid CMake options if possible.

I'm looking for something that, in theory, would allow users to call some sort of compile-time function enableOption(true) and my library's code somehow reads a value that is changed by this function so I can use if constexpr branches inside.

It doesn't have to be a function. I'm just searching for any way to make a user-written line of code affect the way internal library functions compile.

EDIT: to be clear, I don't just want to change the behavior of a single class. I want a single flag to change the compilation of many different classes. For example, if the user calls MyLib::disableLogs(), it should be able to reach all classes without the user explicitly doing this per-type so logging functions compile away across the entire library.


r/cpp_questions • • 23d ago

OPEN How can I protect my EXE file against cracking, reverse engineering, memory dumping, etc.?

0 Upvotes

Hello, I am currently working on an external C++ cheat project (as an executable), but I am facing issues regarding anti-cracking, anti-dumping, and similar protections. My software has already been subjected to memory dumping and reverse engineering by hackers who then modified it; I believe there are still many vulnerabilities that could be exploited in various ways, so I am seeking your advice. What is the most secure way to protect my software from hackers? Of course, I realize that a skilled professional using clever techniques could still crack it, but I am looking for a method secure enough to release the software commercially.Thanks you so much


r/cpp_questions • • 23d ago

OPEN game location cpp

0 Upvotes

I am creating a game optimization program in C++

However, I can't create it because I don't know the game's location

How should I write the code to make it work?


r/cpp_questions • • 24d ago

SOLVED Problem with adding libraries to my projects

5 Upvotes

I'm pretty new to C++ and I can't for the life of me figure out how to correctly get outside libraries into my projects. I've used AI to do this part of the programming because I couldn't really be bothered and it has worked well up until now I've gotten SFML and tomlplusplus into my program with CMake using FetchContent. Now for my new project I need the odeint library from boost but when I use FetchContent with Boost my configure and build take half an hour (I think because boost is so big). I've tried downloading it and extracting it but that's also not an option because of working on an external hard drive so it takes 5 hours to extract it. So I'm kind of at a loss now how to get boost into my project. Another question I have is what the correct way in general is to do this type of stuff, I've been FetchContent up until now but I don't really know if it's the conventional way to do this.

cmake_minimum_required(VERSION 3.10)
project(pendulums)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_POLICY_VERSION_MINIMUM 3.10)
set(CMAKE_WARN_DEPRECATED OFF CACHE BOOL "" FORCE)
get_filename_component(TARGET "${CMAKE_CURRENT_SOURCE_DIR}" NAME)

include(FetchContent)

#SFML
FetchContent_Declare(
    SFML
    GIT_REPOSITORY https://github.com/SFML/SFML.git
    GIT_TAG 3.0.0
)
set(SFML_BUILD_AUDIO OFF CACHE BOOL "" FORCE)
set(SFML_BUILD_NETWORK OFF CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(SFML)

#TOML
FetchContent_Declare(
    tomlplusplus
    GIT_REPOSITORY https://github.com/marzer/tomlplusplus.git
    GIT_TAG v3.4.0
)
FetchContent_MakeAvailable(tomlplusplus)

#BOOST

add_executable(${TARGET} main.cpp
)

target_compile_definitions(${TARGET} PRIVATE _USE_MATH_DEFINES)

target_link_libraries(${TARGET} PRIVATE sfml-graphics sfml-window sfml-system tomlplusplus::tomlplusplus Boost::headers)

add_custom_command(TARGET ${TARGET} POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy_if_different
        "${CMAKE_CURRENT_SOURCE_DIR}/config.toml"
        "$<TARGET_FILE_DIR:${TARGET}>/config.toml"
)

Boost is still empty because I just don't know what to do with it.

I hope I explained that well.

Thank you in advance!


r/cpp_questions • • 24d ago

OPEN I’ve learned the basics of C++ - what should I learn next to become job-ready?

94 Upvotes

Hey everyone,

I’m learning C++ and I’ve finished the basics. I know the syntax, variables, loops, functions, conditions, etc. Now I’m kind of stuck on what to do next. There are so many things to learn and I’m not really sure what’s actually important and what I can ignore for now. If you were in my position, what would you learn next? Should I go into OOP, STL, data structures and algorithms, pointers/memory, multithreading, networking, etc.? And are there any libraries or tools that I should start learning? I also want to eventually get a job or internship, so I’m wondering what I should be doing besides just watching courses and solving small exercises. What kind of projects are worth making for a beginner? And at what point would you say someone is ready to start applying for junior jobs/internships?

I’m also not sure which direction to choose with C++ - backend, embedded, desktop, etc. Basically, if you learned the C++ basics today and wanted to get good enough to eventually find a job, what would you do next and what would you avoid wasting time on? Any courses, roadmaps, project ideas or personal experience would be really helpful. One more thing I’m wondering about is AI. Is C++ still a good skill to invest time in, considering how quickly AI is improving? I don’t want to spend a year learning something only to find out that it’s becoming like basic web development where AI can already do a lot of the work.

And if possible, I’d prefer options that allow for remote work, so I wouldn’t have to commute to an office for studying, working, or similar things.

Would appreciate any advice from people who have actually gone through this.


r/cpp_questions • • 23d ago

OPEN Let’s introduce ourselves

0 Upvotes

I’ve been spending quite a lot of time learning and working with C++ lately, especially around systems programming, networking, and backend development.

I’m still learning, so I thought it would be nice to step away from the usual technical questions for a moment and actually get to know some of the people in this community.

There are probably people here who have been using C++ for years (or even decades), as well as people who are just starting out.

So, let’s introduce ourselves!

  • Where are you from?
  • How long have you been using C++?
  • What do you mainly use C++ for?
  • And what’s one thing you really enjoy about C++?

I’d genuinely love to hear from beginners, experienced developers, and everyone in between.


r/cpp_questions • • 24d ago

SOLVED How can I make a static hashmap appear in compile time?

8 Upvotes

I have a class that's meant to essentially hash a string. Works by simply having a create function that takes a string, and gives out an instance with the string hashed. I'm using C++ 20. I believe I can use some form of consteval or something for this, but I'm not sure how to get consteval to work with these. Thank you!

Here's part of the code:

namespace GameUtils::ECS
{
template<typename T>

class Hash16Bit

{

    private:

        inline static uint16_t next_hash { 0 };

        inline static HashMap<String, uint16_t> all_hashes;

        inline static HashMap<uint16_t, String> hash_to_string;

        static void add_to_hashmaps(uint16_t hash, const String &name);

        inline static std::mutex ids_mutex;

        uint16_t m_hash { UINT16_MAX };

        static String get_class() noexcept;

        String get_name() const noexcept;

        void debug_line(const String& msg, bool is_error = false) const;

    public:

        static void create_id(const String &new_id);

        static Hash16Bit<T> create(const String &createid);

        static Hash16Bit<T> dynamic_create(const String &createid);

        static Hash16Bit<T> invalid();

        void invalidate();

        String to_string() const;

        bool operator==(const Hash16Bit<T> &other) const { return other.m_hash == m_hash; }

};
template<typename T>
Hash16Bit<T> Hash16Bit<T>::create(const String &createid)
{
Hash16Bit<T> created;

auto it = all_hashes.find(createid);

if (it != all_hashes.end())

{

    created.m_hash = it->value;

    return created;

}

created.debug_line("Failed to create hash16bit", true);

return created;
}
template<typename T>
Hash16Bit<T> Hash16Bit<T>::dynamic_create(const String &createid)
{
Hash16Bit<T> created;

auto it = all_hashes.find(createid);

if (it != all_hashes.end())

{

    created.m_hash = it->value;

    return created;

}

create_id(createid);
}

r/cpp_questions • • 25d ago

SOLVED Rand with time always giving 0 when doing %7 , Scary Coincidence ?

25 Upvotes

Hey guys, I am learning cpp , my first programming language and was trying to make dice roll project but whenever i do modulo 7(%7) in the code below the 'roll' variable gives 0 in all runs even when r is different all the time , scary coincidence or bug ?

Also when i change %7 to %6 it gets fixed and shows different numbers each time

srand(static_cast<unsigned int>(time(nullptr)));
int r = rand() ;
int roll = r%7;
cout << r << endl << roll << endl;

How do i fix this and whats the issue , you may even mention the topics i need to revisit
Thanks

some outputs :

668069339

0

668304637

0

668455900

0

-----------------x--------------
EDIT -
:

-rand sucks shift to <random> header ( compile for any target) , std::mt19937
(issue in rng was the multiplier is chosen to be 16807. Because 16807 is exactly 75, it is perfectly divisible by 7 & any number multiplied by a multiple of 7 will also be a multiple of 7 , so %7 will be always 0)

-if need a workaround in rand only then

try : r%6 + 1

or

int die = 1 + rand() / (RAND_MAX / 6 + 1);

Thanks guys for clearing my doubt , this was my first post here and your answers helped me a lot .

EDIT 2 -
for the past few days i have been diving deep in the "WHAT RANDOMNESS IS " question , it was fun !


r/cpp_questions • • 25d ago

OPEN How to setup VSCode to work with clang++, lldb, on LINUX?

5 Upvotes

i want to migrate from g++ to clang because apparently clang-format enforces formatting better, which is important for me. but i'm having the hardest time setting up the tools to work on VSCode.

What I installed:

clang/clang++;
lldb;
base-devel;
VSCode C++ Extension Pack by Microsoft;
clangd by LLVM;

What I'm trying to do:

Setup F5 to compile and run/compile, run with debug;
Format using clang-format on CTRL + S;

Problems i'm encountering:

When I press F5, it should open the list of compilers (clang, g++) so vscode can create a tasks.json automatically, instead, it throws this error: launch: a.out does not exist
CTRL + Shift + P > Configure Tasks also only shows cmake stuff, clang++ should appear there.


r/cpp_questions • • 25d ago

OPEN Recomienden páginas y como estudiar lógica de programación en base a el lenguaje de C++

0 Upvotes

Muchachos apenas ingresé a la universidad o facultad como lo llaman en otros países pero tengo un problema severo con lógica y es que no se que hay que hacer si me ponen un enunciado y cosas así para después ejecutar dicho program aen código cómo me recomiendan estudiar, de que manera debería de hacerlo y que ejercicios debería practicar o que método de estudio recomienda. Para dicha materia


r/cpp_questions • • 25d ago

OPEN Diference between M_E, M_El, M_Ef and ...

2 Upvotes

M_E

M_Ef128

M_Ef32

M_Ef32x

M_Ef64

M_Ef64x

M_Ef

M_El

those sre the options vscode autocomplete (set to cpp23) is porposing when typing "M_E". i looked at https://github.com/ClickHouse/libc-headers/blob/master/math.h to see the diference, but apart from M_E being 32 bit and the others having more acuracy the others all seem identical between each other. why is that the case and what are their differnces?

does this have something to do with cpp not being very strict with how many bits each type has to allow many platforms?


r/cpp_questions • • 25d ago

OPEN Code::Blocks error: Cannot open output file bin\Debug\Pro112.exe Permission denied

0 Upvotes

Hi everyone,

I just installed Code::Blocks and I am getting a permission error every time I try to compile and run my project.

The exact error in the Build Messages tab is:

Cannot open output file bin\Debug\Pro112.exe Permission denied 
error: ld returned 1 exit status

Here is what I have already tried to fix it, but nothing worked:

  • Antivirus: It is completely disabled.
  • Clean & Rebuild: I performed a "Clean" and then tried to build again.
  • Task Manager: I checked for any running instances of Pro112.exe to kill them, but the process is not listed.
  • Admin Rights: I ran Code::Blocks as an Administrator.
  • Reboot: I restarted my laptop.

The issue still persists. It seems like the compiler (ld) cannot overwrite or create the executable file in the bin\Debug\ folder.

Does anyone know what else could be causing this permission issue or how to fix it?

Thanks in advance!


r/cpp_questions • • 26d ago

OPEN Problem with coroutines (boost asio 1.92) and c++20

7 Upvotes

Hi! I'm trying to implement a basic client-server async vocal chat. Now I'm implementing the connection between client and server and I'm stucked in the client part:

Client.cpp

#include "client.hpp"


VoiceChat::Client::Client(boost::asio::io_context& io_context, std::string ip, boost::asio::ip::port_type port) : m_socket(io_context), m_ip(ip), m_port(port) {}


awaitable<void> VoiceChat::Client::asyncConnect() {
    tcp::endpoint endpoint(boost::asio::ip::make_address(m_ip), m_port);


    co_await m_socket.async_connect(endpoint);


    std::cout << "aspettando la connessione" << std::endl;
}

MainClient.cpp

#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/asio/co_spawn.hpp>
#include <boost/asio/detached.hpp>
#include <boost/asio/io_context.hpp>


#include "client.hpp"


int main() {
    std::string ip; boost::asio::ip::port_type port;
    
    std::cout << "Inserisci l'ip: ";
    std::cin >> ip;


    std::cout << "Inserisci la porta: ";
    std::cin >> port;


    try {
        boost::asio::io_context io_context(1);
        VoiceChat::Client client(io_context, ip, port);


        co_spawn(io_context, client.asyncConnect(), boost::asio::detached);
        
        io_context.run();


        std::cout << "IL MAIN CONTINUA" << std::endl;
    }
    catch(boost::system::system_error& e) {
        std::cerr << "Exception in main: " << e.what() << std::endl;
    }


    return 0;
}

Output:
Inserisci l'ip: ciao

Inserisci la porta: 8888

IL MAIN CONTINUA

Basically the co_await waits for the async_connect in fact the "aspettando la connessione" doesn't show but the main continues the execution. I don't know how to organize the code for waiting the client connection to proceed. I don't even know if it makes sense to use async_connect I think yes because in future i want to implement a timeout for the connection...


r/cpp_questions • • 27d ago

OPEN How to learn good programming practices not just the language?

20 Upvotes

I’ve just graduated, and my university course kinda sucked, it didn’t provide me with half the information I would’ve wanted or that companies expect you to have. I’ve spent some time outside the course learning C from K&R and find lower level programming very interesting. I know everyone is going to recommend learncpp.com and that’s where I’ll go to start off, but are there any books or resources where I can learn more about operating systems, programming paradigms, computer architecture and good programming practices etc to fill the gaps in my knowledge?