C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 11-23-2009, 12:59 PM   #1
Registered User
 
Join Date: Nov 2009
Posts: 2
realloc, malloc and file IO, the hell?

Greetings you more seasoned C-linguists.

I come here with a few issues regarding memory and file IO.

Now, first of all, I am only just picking this language up so bear with me :<

So, to learn file IO I decided to write two functions that wrote char-arrays into and from a file, all well and good, except that it doesn't work, it crashes:

funcs.c
Code:
#include <stdlib.h>
#include <stdio.h>
#include "funcs.h"

char* read_file(FILE* fp)
{
    /* Index */
    unsigned int n;
    /* Byte-buffer */
    char* bffr;
    /* Current read byte */
    int token;

    /* Line bellow bugged, makes an array of 4 not 5? */
    bffr =  malloc(5);
    n = 0;

    /* Get tokens untill EOF */
    while((token = fgetc(fp)) != EOF)
    {
        /* If the buffer needs resizing */
        if(sizeof(bffr) == n)
        {
            printf("sizeof(bffr) = %d \nn = %d\n", sizeof(bffr), n);
            printf("Reallocating bffr into size %d ...\n", n+5);
            /* Increase the buffer size by 5 */
            bffr = realloc(bffr, sizeof(bffr)+5);
            printf("new sizeof(bffr) = %d\n", sizeof(bffr));
        }
        /* Add token to buffer as char */
        bffr[n++] = (char)token;
    }
    /* If error doesn't return 0 This crashes the program so its been commented out
   if(ferror(fp))
    {
        return 0;
    }*/

    /* Make the buffer one byte bigger to fit string terminator */
    bffr = realloc(bffr, ++n);
    /* Add string terminator, this crashes the program, so it too has been commented out
    bffr[n] = '\0';*/

    return bffr;
}

int write_file(FILE* fp, char* bffr)
{
    int n = 0;
    /* Put bytes to file untill it returns the wrong value, crashes the program as well
    for(n= 0; fputc(bffr[n], fp) == bffr[n]; n++);*/
    return ++n;
}
main.c
Code:
#include <stdio.h>
#include <string.h>
#include "funcs.h"

int main()
{
    FILE* fp;
    char* bffr;
    char* foutput = "TEST TEEEEEEXT!";

    /* Open file */
    if((fp = fopen("./test.txt", "w+")))
    {
        /* Write data to file */
        if(write_file(fp, foutput) /*== sizeof(foutput)*/)
        {
            printf("Wrote \"%s\" to file\n\n", foutput);
            /* Read data back from file */
            if((bffr = read_file(fp)))
            {
                printf("\n\nSize of string = %d\n%s\n\n", sizeof(bffr), bffr);
            }
            else
            {
                getchar();
                fclose(fp);
                printf("Error reading file into memory.");
                getchar();
                return 1;
            }
        }
        else
        {
            fclose(fp);
            printf("Error writing from memory to file.");
            getchar();
            return 1;
        }
    }
    else
    {
        fclose(fp);
        printf("Error opening file for writing.");
        getchar();
        return 1;
    }
    fclose(fp);

    printf("%s\n%s\n", foutput, bffr);
    if(strcmp(foutput, bffr))
    {
        printf("Success!\n");
        getchar();
        return 0;
    }
    printf("Failed\n");
    getchar();
    return 1;
}

I have identified the problems, I think, but I have no idea why they're happening :S

Either sizeof always returns 4 or all my mallocs and reallocs give me pointers to blocks of 4 bytes.

fputc crashes the program.

I can't add the string terminator at the end, why I can't I don't know; I've been able to add things to the array all the way untill that line.

The input I get into the file seems to be whatever goes through any of the streams.

strcmp also tells me that what I put into the file and what I read from it is the same, even if I never actually write into the file (and yes, the file is empty).

Thanks in advance
Blumfan is offline   Reply With Quote
Old 11-23-2009, 01:03 PM   #2
C++ Witch
 
laserlight's Avatar
 
Join Date: Oct 2003
Location: Singapore
Posts: 12,460
Quote:
Originally Posted by Blumfan
Either sizeof always returns 4 or all my mallocs and reallocs give me pointers to blocks of 4 bytes.
According to what you have observed, those pointers are 4 bytes in size, i.e., you cannot use sizeof to determine the size of an array given just a pointer to the first element of that array.
__________________
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar

Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
laserlight is online now   Reply With Quote
Old 11-23-2009, 01:46 PM   #3
Registered User
 
Join Date: Nov 2009
Posts: 2
Now that you say it, it makes a whole lot of sense ...

Is there an easier way of getting its size except a variable containing the value? D= Because that feels like a very ugly method.
Blumfan is offline   Reply With Quote
Old 11-23-2009, 02:01 PM   #4
Registered User
 
Join Date: Sep 2004
Location: California
Posts: 3,029
Quote:
Originally Posted by Blumfan View Post
Now that you say it, it makes a whole lot of sense ...

Is there an easier way of getting its size except a variable containing the value? D= Because that feels like a very ugly method.
A separate variable containing the size is the common way of doing it. You can also do something like #define BUFFER_SIZE 5.
__________________
bit∙hub [bit-huhb] n. A source and destination for information.
bithub is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
File Writing Problem polskash C Programming 3 02-13-2009 10:47 AM
sequential file program needhelpbad C Programming 80 06-08-2008 01:04 PM
To find the memory leaks without using any tools asadullah C Programming 2 05-12-2008 07:54 AM
Game Pointer Trouble? Drahcir C Programming 8 02-04-2006 02:53 AM
Problem with malloc() and sorting words from text file goron350 C Programming 11 11-30-2004 10:01 AM


All times are GMT -6. The time now is 12:18 AM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22