c++heap-memorystack-memoryhardcode

What is the difference between "hard-coding" and passing in arguments in regard to memory?


So the title is my question. In memory, arguments can be located on the stack or heap depending on how they are initialized, but how is hard-coded information dealt with?

As an example, I will use the constructor for ifstream

What is the difference between this:

void function(){

    ifstream infile("home/some/file/path");

}

vs

void function(char* filePath){

    ifstream infile(filePath); //filePath points to a character array which contains home/some/file/path

}

Could any memory implications arise from the use of one over the other? (Multithreading could lead to heap corruption if the char* isn't free'd correctly? etc).

I am just trying to understand the difference and possible implications so I can apply the answer to a larger problem. All insight is welcome and feel free to correct me if I've made any incorrect statements/assumptions!


Solution

  • Literals (which is what your first example shows) are placed into the static initialization portion of the executable (which is why, if you are on a *Nix system), you can use the command strings and obtain a list of all the literals in the application.

    Your 2nd example should actually be modified to

    void function(const char* filePath) { ... }
    

    Unless you are going to modify the pointer in the function. The memory for that function can come from anywhere (a string literal being passed into the function, a constant string declared somewhere else in the application, a string stored in memory and inputted from the command line or console, etc.)

    The primary issue you will run into with Multithreading here is if 2+ threads are attempting to load the same file at the same time. It may not be a problem if they are all reading it, but if you have a thread that wants to write to it and obtains an exclusive lock on the file, the other threads will deadlock. This isn't directly related to your strings question, though.