Подскажите, где я не освобождаю память и с каждой итерацией цикла она утекает?
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
char *str_cpy(const char *str0, const char *str1) {
char *str;
if ((str = malloc(strlen(str0) + strlen(str1) + 1)) != NULL) {
str[0] = '\0';
strcat(str, str0);
strcat(str, str1);
}
return str;
}
bool fs_isdir(const char *path) {
struct stat sb;
if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode))
return true;
return false;
}
bool net_exists_interface(const char* interface) {
DIR *dir = opendir("/sys/class/net");
if (dir != NULL) {
struct dirent *ent;
while ((ent = readdir(dir)) != NULL) {
char *path = str_cpy("/sys/class/net/", ent->d_name);
if (strcmp(ent->d_name, interface) == 0 && fs_isdir(path)) {
free(path);
return true;
}
free(path);
}
}
return false;
}
void net_stat_interface(const char *interface) {
puts(interface);
}
void net_stat(char *interfaces[]) {
for (int i = 0; interfaces[i] != NULL; i++) {
if (net_exists_interface(interfaces[i]))
net_stat_interface(interfaces[i]);
}
}
int main() {
char *interfaces[] = {"eth0", "lo", "ccmni0", "tralala"};
while (true) {
net_stat(interfaces);
sleep(1);
//cpu_stat();
//mem_stat();
}
return 0;
}
opendir/readdir
- здесь вы наверно потеряете. Внизу обязательноclosedir(dir)
closedir
- то надо? Да, согласен, readdir зря указал