Thread: Dynamic memory allocation for file handling

  1. #1
    Registered User
    Join Date
    Nov 2002
    Posts
    1

    Dynamic memory allocation for file handling

    Hi

    I am processing soem text files in C using dyanmic memory allocation where I need to compare 2 files with 100000 records.
    the code is

    FILE *f;
    char s[10],s1[10];
    char a[LIMIT][10],a1[LIMIT][10];//LIMIT = 100000

    int x=0,y,i=0,j=0,k,i_sec=0,j_sec=0,k_sec,k_comp,l_com p,q;

    //master.txt is the masterfile.Ex: G11

    f=(FILE *)malloc(100000);

    f=fopen("C:/WIN95/Desktop/master.txt","r");

    if (!f)
    return 1;

    while ((fgets(s,11,f)!= NULL) && (i < LIMIT)) //fgets reads a string from the file
    {

    strcpy(a[i],s);
    //printf("% d ---- %s\n",i,a[i]);
    ++i;
    }

    k=i;

    //printf("k= %d",k);

    free(f);
    fclose(f);

    But I get a memeory error; perhaps exceeding the heap allocation.

    I will be very thankful if you can help me here.
    Last edited by prashanth_sh; 11-07-2002 at 06:23 AM.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    f=(FILE *)malloc(sizeof(FILE));
    What the hell are you doing? You don't allocate space for file pointers. Furthermore, don't typecast your malloc returns. This isn't C++ so there's no point in ever doing so.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    Code:
    while ((fgets(s,11,f)!= NULL)
    Buffer overflow, you have only space for 10 characters. Change it to:
    Code:
    while ((fgets(s,10,f)!= NULL)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  2. Replies: 16
    Last Post: 01-01-2008, 04:07 PM
  3. dynamic memory allocation problem
    By firyace in forum C Programming
    Replies: 4
    Last Post: 05-23-2007, 09:57 PM
  4. Dynamic memory allocation...
    By dicorr in forum C Programming
    Replies: 1
    Last Post: 06-24-2006, 03:59 AM
  5. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM