I'm having an error in my code I can't figure out. At first I thought it was an error on malloc() or sysctl(), but it seems it's neither. Since I'm all out of options, I'm posting it here.
Code:
int main() {
char *systemName;
printf("system information:\n");
systemName = sysName();
printf("\toperating system:\t\t%s\n", systemName);
free(systemName);
return 0;
}
char *sysName() {
int mib[2];
size_t length;
char *osName;
if((osName = (char *)malloc(50)) == NULL) {
printf("Error on malloc(), no memory allocated\n");
}
memset(osName, 0, 50);
mib[0] = CTL_KERN;
mib[1] = KERN_OSTYPE;
length = sizeof(osName);
sysctl(mib, 2, &osName, &length, NULL, 0);
error(); // a function that checks errno
return osName;
}
The operating system name is not printed out; the line is just blank. If I set osName to be, i.e. 'A': osName[0] = 'A' the A is printed out. This leaves me thinking it's something wrong with sysctl(), but I've used the function the exact same way in another program - where it works! Can anyone see what's wrong? Help appreciated.