Ethan Fox
Ethan Fox

Reputation: 169

"realloc(): Invalid pointer" error

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!

Upvotes: 0

Views: 2220

Answers (1)

John3136
John3136

Reputation: 29266

char* path = malloc(size_path*sizeof(char));
path = "./storage/\0";

So path points to some dynamically allocated memory, then on the next line you say path = something_else so:

  1. You've leaked the dynamically allocated memory (because you don't have a pointer to it anymore, so can't get access to it to free it)
  2. You can't realloc non dynamic memory

Reading between the lines of the question, I'd suggest you don't even need dynamic memory at all. You can just use a fixed size buffer:

char path[128]; // arbitrary limit that we "know" is ok given our data
char* filename = "test.txt";
sprintf(path, "/storage/%s", filename);

Obviously this is tailored to assume filename could actually change based on some data, otherwise the whole lot could be one literal string.

Upvotes: 3

Related Questions