0

Programs related to my uni classes are automatically tested by uni's custom system and have to meet certain requirements, one being not allocating more than you need. I've been trying to find a way to see how much memory is allocated at given points but can't figure it out (I'm using CLion). This would rapidly increase the rate of solving these problems and decrease amount of frustration I get when trying to find where am I allocating that one byte too much.

Edit: Imagine I have to allocate an array of x pointers (x being i.e. amount of lines in a file), each of them having different amounts of ints. At some point in the code my calculations are wrong and there is too much memory being allocated which is then never used. Is it possible to "lookup" the memory at a given breakpoint?

navivix
  • 1
  • 1
  • When you write your program, you should *know* how much it is allocating. Any memory allocation *bugs* can be tracked down by using something like Valgrind. – Eugene Sh. Apr 26 '21 at 14:58
  • But those aren't bugs. It's just that I'm allocating too much due to things like wrong logic or incorrect maths. Programs themself work fine, but have a couple of allocated bytes here and there that are not necessary. Also Valgrind usually shows no errors since memory is allocated and freed correctly, but there's just too much of it and tests are very strict about it (one byte too much and it won't pass) – navivix Apr 26 '21 at 15:02
  • Well then don't allocate them. – anastaciu Apr 26 '21 at 15:04
  • There is no portable way of doing it, it deppends on the system you are using. – anastaciu Apr 26 '21 at 15:05
  • 3
    Re “But those aren't bugs”: A bug is a deviation from specification. When the specification of a program says it should not allocate too much memory, and the program allocates too much memory, that is a bug. Do not think of bugs just as “the program prints strange output” or “the program prints wrong results.” Engineering is designing things to conform to specifications, not just making computers do stuff. – Eric Postpischil Apr 26 '21 at 15:06
  • Look [here](https://stackoverflow.com/a/1281720/6865932), though by your description you should be able to find the extra memory without this. – anastaciu Apr 26 '21 at 15:17
  • Well I thought there might be a way of doing that inside of an IDE, but I can just print out the result of _msize, so I guess that would be the answer. – navivix Apr 26 '21 at 15:24

1 Answers1

0

You can use popen to execute a terminal command and get its output. Using this, you can call free or cat /proc/meminfo (in Linux) from within your program to get system-wide memory info, including available memory.

Be aware that you might still run into memory issues if the amount of free memory has changed between the time these memory commands run and you next try to allocate.

wxz
  • 1,002
  • 4
  • 16