Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

As the title states, I\'d like to know if coding style can cause or influence me

ID: 652707 • Letter: A

Question

As the title states, I'd like to know if coding style can cause or influence memory fragmentation in a native application, specifically one written using C++. If it does, I'd like to know how.

An example of what I mean by coding style is using std::string to represent strings (even static strings) and perform operations on them instead of using the C Library (such as strcmp, strlen, and so on) which can work both on dynamic strings and static strings (the latter point is beneficial since it does not require an additional allocation to access string functions, which is not the case with std::string).

A "forward-looking" attitude I have with C++ is to not use the CRT, since to do so would, in a way, be a step backwards. However, such a style results in more dynamic allocations, and especially for a long living application like a server, this causes some speculation that memory fragmentation might become a problem.

Explanation / Answer

The question and the supporting text don't match up.

Your supporting text is talking about comparing two libraries' memory usage, which can be tested fairly directly and is orthogonal to coding style. Just wrap up the C string operators in a thin C++-style object and you can work with them the same with little-to-any memory impact, for instance.

The question title implies difference in actual style, such as allocating/destroying objects as needed versus using an object pool, or constructing strings with imperative loops of logic and concatenation intertwined versus building up an array of strings imperatively and then constructing the final string all at once.

The answer to both, however, is the same: yes, they can influence memory fragmentation -- the underlying libraries work in different ways so they probably affect the memory in different ways, and your usage of the libraries can also impact memory fragmentation, and the "proper" style probably depends on the library that you're using.

C-style string manipulation can be very light on memory and better controlled for fragmentation issues, but you will pepper your executable with variables to keep track of the state of your output string as you assemble it, and if you don't put a lot of effort into it, you probably won't beat std::string's code for common use-cases. Of course, if you have no idea how std::string works behind-the-scenes, you could also make it do something stupid, but that's for you to decide on how much you want to learn the internals of your tools and how much it actually impacts what you're trying to accomplish.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote