-1

I'm in trouble in this code with the fileContent variable.. I wish that the changes made by fileReader reallocation works fine in my main, but it doesn't work..

void fileReader(char *fileName, char *fileContent){
    FILE *inputFile = fopen(fileName, "r");

    int fileLength = 0;
    int endFlag = fgetc(inputFile);

    while(endFlag != EOF){
        fileContent = (char *) realloc (fileContent, (fileLength + 1) * sizeof(char));
        fileContent[fileLength] = endFlag;
        endFlag = fgetc(inputFile);

        fileLength++;
    }
}

int main(int argc, char const *argv[]){
    char *fileName = (char *) malloc (sizeof(char));
    char *taskStack = (char *) malloc (sizeof(char));
    char *fileContent = NULL;

    inputReader(fileName, taskStack);
    fileReader(fileName, fileContent);


    return 0;
}
GSchimiti
  • 43
  • 1
  • 7
  • What do you intend to do, and what output do you expect? – mohit Aug 02 '13 at 06:18
  • You should not do `p = realloc(p, ...)`. If `realloc` fails, you've lost your reference to `p` and will leak the memory. Of course, you're not checking that `realloc` succeeded either... – jamesdlin Aug 02 '13 at 06:31
  • **[Do *not* friggin' cast the return value of `malloc()`!!!](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858)** –  Aug 02 '13 at 06:31

1 Answers1

6

It is a waste of performance to realloc char by char, instead you can think about working with reasonable sized chunks. Anyway, pass a pointer to the fileContent:

void fileReader(char *fileName, char **fileContent){
   /* ... */
   fileContent[0] = (char *) realloc (fileContent[0], 
          (fileLength + 1) * sizeof(char));

and in the main:

fileReader(fileName, &fileContent);

so that the updates to the pointer is visible outside the function.

perreal
  • 94,503
  • 21
  • 155
  • 181
  • Interesting: The use of the `[0]` operator instead of dereferencing using the `*` operator. – alk Aug 02 '13 at 08:19
  • As a side note on the performance issue: Increasing any allocation by fixed sized chunks gives quadratic complexity O(n^2), increasing an allocation by a constant _factor_ gives linear complexity O(n). This is why most such reallocation schemes use the factor approach. – cmaster - reinstate monica Aug 02 '13 at 09:16
  • @perreal.. You know why the (char *) used in function parameter isn't visible outside the function in this streaming case, but in case of stdin streaming it works? – GSchimiti Aug 31 '13 at 04:05
  • 1
    How does it work in stdin case? If you mean scanf, it doesn't assign a new value to the pointer via realloc, it just modifies the characters pointed by the pointer. – perreal Aug 31 '13 at 04:09