Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Why is this making my program crash ?

realloc

  • Please log in to reply
5 replies to this topic

#1 Moudi

Moudi

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 131 posts

Posted 03 April 2010 - 02:52 PM

                FILE *fe;
            fe = fopen("mydatabase.dbs", "rb+");
            i=0;
            char cc;
            char *note = NULL;
            while((cc=fgetc(fe))!=EOF)
            {
                realloc(note, i+2);
                strcat(note, cc);
                i++;
            }
            rewind(fe);
            fclose(fe);

I tried using safe method, tried casting it to char, tried transfering data to a temp with sscanf, tried fgets, tried everything, the program is crashing at
strcat(note, cc);

if i remove that line, it runs perfectly.. any idea what i should do ?

Thanks in advance
  • 0

#2 bobdark

bobdark

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 155 posts

Posted 03 April 2010 - 04:11 PM

how about replacing it with
strcat(note, &cc);

  • 0

#3 Moudi

Moudi

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 131 posts

Posted 03 April 2010 - 04:34 PM

still crashing, but crashes 1 second late
  • 0

#4 bobdark

bobdark

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 155 posts

Posted 03 April 2010 - 07:57 PM

Thats because you don't assign the value returned by realloc to note. That means note stays NULL and later you attempt writing to NULL address.
  • 0

#5 Ancient Dragon

Ancient Dragon

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 378 posts

Posted 03 April 2010 - 09:06 PM

Needs to be
note =  realloc(note, i+2);

>>strcat(note, cc);
That can't work. strcat() expects the second parameter to be a null terminated string, which cc is not.


Also that way of allocating memory is grossly inefficient. A more efficient method is to allocate memory in larger chunks and only realloc when the memory chunk is filled up.
const int blocksize = 255; // allocate 255 bytes at a time
char* note = NULL;
size_t cursize = 0; // current allocated size
size_t used = 0; // number of bytes used

          while((cc=fgetc(fe))!=EOF)
         {
                if( (used +1) >= cursize)
                {
                    cursize += blocksize;
                    note = realloc(note, cursize);
               }
                note[used++] = cc;
            }

  • 0
Visit Grandpa's Forums, a social networking forum, with family-oriented arcade games, blogs, discussion forums, and photo albums.

#6 Moudi

Moudi

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 131 posts

Posted 04 April 2010 - 01:37 AM

Ancient Dragon, thanks alot ! It worked :)
  • 0





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download