I'm working on some code for school, and here's the fragment of code that I'm having some trouble with:
// Create file path
int size_path = 11;
char* path = malloc(size_path*sizeof(char));
path = "./storage/\0";
for(i = 0; i < size_filename; i++){
size_path++;
path = realloc(path, size_path*sizeof(char));
path[size_path-1] = filename[i];
}
path[size_path] = '\0';
Essentially, what I am doing is trying to find the existence of a file (for example, test.txt) and so I need to use access() to check it's existence, but first I need to build the path itself such that path = "./storage/test.txt" I've already used the method above to parse some other stuff, so I know the way I'm doing it works, I just think I'm missing something here because whenever I try to run the code, I get an error in the compiler: *** Error in ./a.out: realloc(): invalid pointer: 0x00000000004016c7 ***
I'm curious to see what insight you guys can provide me because I've been working on this bug for at least a half hour though and the community has helped me solve numerous problems in a matter of minutes, so I'm sure it's just an off-by-one thing but I can't really figure out where it would be. Thanks in advance!
EDIT: As I imagined, I got the answer to my question in under 5 minutes. Turns out, I was accidentally leaking the dynamically allocated memory by not actually putting anything into it and statically allocating it directly afterwards. Instead, I've used strcpy(path, "./storage/") and I got exactly the functionality I was looking for. Thank you!
path = "./storage/\0";assignspathwhich was just initialized withchar* path = malloc(size_path*sizeof(char));That leaks the previous allocation.path = "./storage/\0";should bestrcpy(path, "./storage/");strcpy(path, "./storage/");same effect asstrcpy(path, "./storage/\0");realloc(path, size_path*sizeof(char));too small for finalpath[size_path] = '\0';