-4

I have a doubt dealing with pointers in C. During my program execution I must open and close a configuration file but since a different program updates its content i must do this several times while the program runs. So i made a little function which reads the file and closes it and i call it every time I need it.

int readConfigFile()
{
    FILE* pfile = fopen("path to file", "r");
    fseek(pFile, 0, SEEK_END);
    lSize = ftell(pFile);
    rewind(pFile);

    text = (char*)malloc(sizeof(char) * lSize);
    if (text == NULL) {
        fputs("Memory error", stderr);
        return (0);
    }
    if (fread(text, 1, lSize, pFile) <= 0) {
        printf("Nothing read");
        return 0;
    }

    text[lSize] = '\0';
    //Do the actual reading
}

If i am not mistaken this functions creates a new FILE* pointer every time it runs however I was wondering if using a FILE* pointer with a larger scope and recycling it every time the function runs would be better. Meaning:

FILE* globalVaraible;
int readConfigFile(FILE* pFile)
{
    *pfile = fopen("path to file", "r");
    //Do some stuff here
}

I am worried that, since there is no garbage collector in C++ as far as i know, the first function will create too many FILE* pointers ,if runs for long enough, and overflow my memory. On the other hand having a global pointer, that will open and close in the context of a single function, seems rather wasteful and not very modular, at least for my point of view.

So should I recycle my pointer, or any reference for that matter, or is it okay to declare new ones as needed?

Thanks in advance.

Coyo
  • 11
  • 1
  • 3
  • 1
    The `FILE*` pointer is a local automatic variable to `readConfigFile`. It is cleaned up automatically when the function exits. You should close the file at the end of the function tough. In C++ you should use file streams. – Unimportant Jan 05 '17 at 19:50
  • 4
    I would not use any of this in `c++` – drescherjm Jan 05 '17 at 19:51
  • 4
    Is this a C question or a C++ question? The answers are subtly different. – David Schwartz Jan 05 '17 at 19:51
  • 2
    FYI you cannot recycle references. Once initialized they can never be changed. – NathanOliver Jan 05 '17 at 19:52
  • 1
    All you need to worry about is calling `fclose()` on the file descriptor once you are done with it. – SergeyA Jan 05 '17 at 19:54
  • of graver concern to me is the `text` you are `malloc`ing each time the function is called. If you're not `free`ing that anywhere you have a memory leak. If your `fread(..)` condition is true, you will `return 0;` without `free`ing `text` – yano Jan 05 '17 at 19:55
  • This pointer is a local non-`static` variable, and it's _destroyed_ once control reaches end of the function it's local to. Otherwise, if it didn't work like this, imagine what tremendous amount of memory would computers need to run some simple programs. Also, _why_ keep that pointer alive? It's useless as soon as the function exits. – ForceBru Jan 05 '17 at 19:57
  • 2
    Please, please, stop working on this code, [get a good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list?lq=1) and actually learn the language before you continue. What you've written here is ancient C style code that no one should write anymore. Your question shows you don't understand the lifetime of objects in static, automatic, and dynamic storage. – Rob K Jan 05 '17 at 20:01
  • please don't mind me asking why the question gets down voted; it's just to understand the rules of SO - but what's actually wrong with the question? – Stephan Lechner Jan 05 '17 at 20:03
  • 1) C and C++ are different languages. C for instance does not support references. 2) You should only recycle if you use regenerative power sources for it. With fossile or nuclear power, recycling is often worse than creating new products. 3) This question is too opiniated for this site. – too honest for this site Jan 05 '17 at 20:03
  • Don't worry about the pointer--it's destroyed automatically on scope exit. Worry about the resources you're grabbing that you're *never* releasing, that *aren't* destroyed automatically on scope exit. There is a difference here between resources and the pointers that point to them, and you should probably learn it, along with lots of other things you can find in a C++ book. Seriously, go read one. – jaggedSpire Jan 05 '17 at 20:05
  • 2
    @StephanLechner probably for violating the unspoken rule where the questioner should have a minimal understanding of the topics they're asking about. As it is, the question shows enough misunderstandings of the topic at hand, that an answer valuable to OP would have to address how variable lifetimes work, the difference between pointers and what they point to, and probably also RAII and C++ streams, *on top* of explaining why they shouldn't use malloc for buffers on a high level, what they *should* use and why they don't even want a buffer here. In other words, a good answer would be too long. – jaggedSpire Jan 05 '17 at 20:17

1 Answers1

0

You could use freopen().

http://en.cppreference.com/w/cpp/io/c/freopen

There is no guarantee that it will actually reuse dynamic memory allocated for the "old" file. This function may as well be a wrapper for fclose() and fopen() - it's all implementation defined.

From what I see, newlib (a popular libc for embedded targets) reuses the FILE storage, so there's a small gain here. Whether or not it makes a noticeable difference is another matter.

https://sourceware.org/git/gitweb.cgi?p=newlib-cygwin.git;a=blob;f=newlib/libc/stdio/freopen.c;h=fb1f6c4db3f294f672d7e6998e8c69215b7482c1;hb=HEAD

Freddie Chopin
  • 8,440
  • 2
  • 28
  • 58