I feel like I have shored up loose ends, but CLion keeps saying I have a memory leak possible from main attached to the “files” var.
That being said, I am curious is there a util or toolset that will help me narrow down any potential issues like this better than the stock toolsets? That is the primary question! New to C coming from py and go. These are not issue way up on those high level langs… lol
example code below and an example of the amazingly help warning clion gives.
“Allocated memory is leaked when called from function ‘main'”
“Leak of memory allocated in function ‘get_files'”
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <commdlg.h>
#include "log.h"
char** get_files(int* file_count) {
OPENFILENAME ofn;
char* szFile = malloc(8192 * sizeof(char));
char** files = NULL;
*file_count = 0;
if (szFile == NULL) {
return NULL;
}
// Initialize OPENFILENAME
szFile[0] = '';
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrFile = szFile;
ofn.nMaxFile = 8192;
ofn.lpstrFilter = "All Files*.*Text Files*.TXTCSV Files*.CSVDAT Files*.DAT";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_ALLOWMULTISELECT | OFN_EXPLORER;
if (GetOpenFileName(&ofn) == TRUE) {
char* ptr = ofn.lpstrFile;
if (*(ptr + strlen(ptr) + 1) == '') {
// Single file case
*file_count = 1;
files = malloc(2 * sizeof(char*));
if (files == NULL) {
free(szFile);
return NULL;
}
files[0] = strdup(ptr);
if (files[0] == NULL) {
free(files);
free(szFile);
return NULL;
}
files[1] = NULL;
} else {
char* dir = ptr;
ptr += strlen(ptr) + 1;
int count = 0;
while (*ptr) {
count++;
ptr += strlen(ptr) + 1;
}
*file_count = count;
files = malloc((count + 1) * sizeof(char*));
if (files == NULL) {
free(szFile);
return NULL;
}
ptr = ofn.lpstrFile + strlen(ofn.lpstrFile) + 1;
for (int i = 0; i < count; i++) {
files[i] = malloc(strlen(dir) + strlen(ptr) + 2);
if (files[i] == NULL) {
for (int j = 0; j < i; j++) {
free(files[j]);
}
free(files);
free(szFile);
return NULL;
}
sprintf(files[i], "%s\%s", dir, ptr);
ptr += strlen(ptr) + 1;
}
files[count] = NULL;
}
}
free(szFile);
return files;
}
int main(void) {
Info(__func__, "Starting file validation routine");
int file_count = 0;
char** files = get_files(&file_count);
if (files == NULL) {
Info(__func__, "Getting the files to process failed");
return 1;
}
for (int i = 0; i < file_count; i++) {
char* shortName = strrchr(files[i], '\');
if (shortName != NULL) {
shortName++;
const size_t bufferSize = strlen("Validating: ") + strlen(shortName) + 1;
char* message = malloc(bufferSize);
if (message != NULL) {
snprintf(message, bufferSize, "Validating: %s", shortName);
Info(__func__, message);
free(message);
}
}
free(files[i]);
}
free(files);
return 0;
}
While helping debug my crap code is not part of the question, if you can see where I was dumb and want to help, feel free… lol
4