We're trying to find out how much physical memory is installed in a machine running Mac OS X. We've found the BSD function sysctl(). The problem is this function wants to return a 32 bit value but some Macs are able to address up to 32 GB which will not fit in a 32 bit value. (Actually even 4 GB won't fit in a 32 bit value.) Is there another API available on OS X (10.4 or later) that will give us this info?
Asked
Active
Viewed 1.1k times
4 Answers
14
The answer is to use sysctl to get hw.memsize as was suggested in a previous answer. Here's the actual code for doing that.
#include <sys/types.h>
#include <sys/sysctl.h>
...
int mib[2];
int64_t physical_memory;
size_t length;
// Get the Physical memory size
mib[0] = CTL_HW;
mib[1] = HW_MEMSIZE;
length = sizeof(int64_t);
sysctl(mib, 2, &physical_memory, &length, NULL, 0);

Michael Taylor
- 2,063
- 1
- 13
- 12
-
A minor correction: sizeof(int64) should be sizeof(int64_t) – Chih-Hsuan Yen Sep 27 '17 at 17:37
5
Did you try googling?
This seems to be the answer: http://lists.apple.com/archives/scitech/2005/Aug/msg00004.html
sysctl() does work, you just need to fetch hw.memsize instead of hw.physmem. hw.memsize will give you a uint64_t, so no 32 bit problem.

sleske
- 81,358
- 34
- 189
- 227
4

Community
- 1
- 1

dmckee --- ex-moderator kitten
- 98,632
- 24
- 142
- 234
-
1Nice & easy for scripting! Also if you only want memory: `sysctl hw.memsize` or `sysctl -a | grep mem` – TrinitronX Dec 03 '13 at 22:44
-
Note: hw.physmem and hw.usermem will return smaller values for systems over [2GB RAM](http://superuser.com/questions/197059/mac-os-x-sysctl-get-total-and-free-memory-size#comment199969_197085) [muc.lists.FreeBSD.hackers Discussion](https://groups.google.com/d/msg/muc.lists.freebsd.hackers/P58uQQcRiSo/1lAwPcOfsYIJ) See `/usr/include/sys/sysctl.h` comments for more info. – TrinitronX Dec 03 '13 at 23:04
0
Alternatively you can add the data from vm_statistics_data_t to get the total memory
vm_statistics_data_t vm_stat;
int count = HOST_VM_INFO_COUNT;
kern_return_t kernReturn = host_statistics(mach_host_self(), HOST_VM_INFO, (integer_t*)&vm_stat, (mach_msg_type_number_t*)&count);

valexa
- 4,462
- 32
- 48
-
I am getting a warning here: "Implicit declaration of function 'host_statistics' is invalid in C99", how do I fix this? – Jeremiah Smith Dec 12 '13 at 10:18
-
-
Thanks @valexa, but it doesn't work, even with adding the Kernel.framework, it will show an error on the line saying it does not exist. The warning is not an error, so it has do with deprecated code somewhat. Perhaps you have an idea? – Jeremiah Smith Dec 30 '13 at 17:31
-
I fixed the error by including `#import
` and also updated the function to 64-bit via host_statistics64. – Jeremiah Smith Dec 30 '13 at 18:19