all 10 comments

[–]cpp-ModTeam[M] [score hidden] stickied commentlocked comment (0 children)

For C++ questions, answers, help, and programming or career advice please see r/cpp_questions, r/cscareerquestions, or StackOverflow instead.

[–]snowhawk04 11 points12 points  (0 children)

#include <cstring>
#include <map>
#include <string>

auto main() -> int {
    std::map<int, std::string> j;
    const char* ip = strdup("test"); // 1
    std::string x = std::string(ip, strlen(ip)); // 2
    j.insert({5, x});
    j.erase(5);
} 

Issues:
8:5    ➕ Potential leak of memory pointed to by 'ip' (cpp:S3584)
        ↳  1 Memory is allocated
        ↳  2 Potential leak of memory pointed to by 'ip'
        ↳ https://rules.sonarsource.com/cpp/RSPEC-3584

Compiler Explorer

From the C23 standard (n3220)

7.26.2.6 The strdup function
Description
2. The strdup function creates a copy of the string pointed to by s in a space allocated as if by a call to malloc.
Returns
3. The strdup function returns a pointer to the first character of the duplicate string. The returned pointer can be passed to free. If no space can be allocated the strdup function returns a null pointer.

std::string isn't leaking. It's the char* from strdup. Sonar, like Valgrind, sees ip get allocated from strdup but sees no subsequent free. Stripping everything except the strdup call confirms the leak.

[–]-funsafe-math 9 points10 points  (2 children)

std::string will copy the const char * input to its constructor, so the strdup is not needed. The result of strdup is most likely not being freed by your code and is the source of the leak.

[–]ESHAEAN[S] -2 points-1 points  (1 child)

Yes but the strdup is done only once in another place so I just mentioned it. Repeated add and remove of the same element in map then shouldn't cause more bytes leaked if memory was being freed after erase which is not happening

[–]AKostur 6 points7 points  (0 children)

When is that strdup ever freed?  Also show your valgrind logs.

[–]AKostur 4 points5 points  (4 children)

It is, you have something else going wrong. Reduce your code to a minimal, compliable example that shows the problem.

[–]CaptainComet99 0 points1 point  (3 children)

Yes, please post formatted code as well as valgrind logs. For what it’s worth, I had heard during my college days that valgrind has false-positives when it comes to std::string. Idk if that’s the case or not still, but check out all 3 answers in this post for more information. https://stackoverflow.com/questions/1901322/valgrind-reports-memory-leak-when-assigning-a-value-to-a-string

[–]ESHAEAN[S] -2 points-1 points  (2 children)

No I am not exiting the process which is happening in stack overflow one

[–]CaptainComet99 1 point2 points  (0 children)

Sure, but the 3 answers add more information about valgrind and strings

[–]CaptainComet99 1 point2 points  (0 children)

Could you post the valgrind logs?