1

Now I'm studying vector of structs, and attempt to print it after sorting by ppid. In this process, I want to test "'the string value' is saved well", but some junk value is saved this space like below picture.

enter image description here

:: Second value "contest.exe" is saved well,

::but, as you see, the first value "Microsoft.VsHub~" is saved like "?(triangle)"

Why this problem occured, and how to solved it?

This is my structure,

struct process {
    string procName;
    DWORD procPid;
    DWORD procPpid;
};

main(){
    ...
    std::vector <process*> myProcess;
    ...
}

Save value like,

    process* p = new process();
    p->procName = pe32.szExeFile;
    p->procPid = pe32.th32ProcessID;
    p->procPpid = pe32.th32ParentProcessID;

    myProcess.push_back(p);

and print this

    _tprintf(TEXT("[%s]"), pe32.szExeFile);
    _tprintf(TEXT(" %s \n"), myProcess[i]);
    _tprintf(TEXT("[%d]"), myProcess[i]->procPid);
5
  • 2
    In general, avoid naked pointers in STL containers, use smart pointers instead. Commented Apr 11, 2016 at 12:14
  • Is string a std::string? Commented Apr 11, 2016 at 12:15
  • 1
    In general, avoid pointers where possible. Store elements by value (std::vector<process>) instead. Commented Apr 11, 2016 at 12:20
  • @Pixelchemist - pointers are core to the language and having referring-only pointers in a vector is no problem. It's when they the vector has ownership of the pointers that issues tend to stack up. Then use whole objects/values if possible and smart pointers otherwise, the type of which should be determined by the sharing needs. Commented Apr 11, 2016 at 13:11
  • @JohannGerell: Non-ownership is when storage by value is not suitable but the code that is part of the question indicates that storing by value is probably the best choice here. Not only because a vector of values is more versatile (elements copyable, moveable, ...) but also because of performance considerations (adjacent storage, cache effects, ...) My recommendation holds. For ownership: value > smart pointer > pointer. Commented Apr 11, 2016 at 13:36

1 Answer 1

1

By doing

_tprintf(TEXT(" %s \n"), myProcess[i]);

you try to print the content of the process* in the myProcess vector at index i as a null terminated string. Try myProcess[i]->procName.c_str() instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Time limit will be end soon :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.