GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 01-Feb-2008, 08:08
aijazbaig1's Avatar
aijazbaig1 aijazbaig1 is offline
Member
 
Join Date: May 2006
Location: Sweden
Posts: 141
aijazbaig1 has a spectacular aura about

Segmentation fault issues with 'realloc'


Hello there,
I am trying to implement a custom gets function which would allow me to read a string so as to avaoid the pitfalls associated with the C version of 'gets' as mentioned here.

Well...I have been able to get some breakthrough into it. What my function does it that it keeps on extending the buffer (to hold the string) size by 16 if the user enters a string longer than 16 until it encounters the '\n' character. Im doing a char by char read using getchar and i check for the '\n' character and for the number of chars entered as of yet.

So if the user string is more than 4(size of the original buffer) but less than 16, it works fine though it only displays the first 4 chars..but if the user string is >16 then issues do arise.

Im wondering why...the seg fault occurs at the line preceded by an arrow-head in the program below

Heres the whole deal:
CPP / C++ / C Code:
// the main program taken from the test thread by walt..modified with the header


#include <stdio.h>
#include "mygets1.h"

int main()
{
    char  b1[] = "ABCD";
    char  b2[] = "LMNO";
    char  b3[] = "ZYXW";
    
    puts(b1);
    puts(b2);
    puts(b3);
    putchar('\n');
    
    puts("Enter some characters:");
    mygets(b2);

    putchar('\n');
    puts(b1);
    puts(b2);
    puts(b3);
    
    return(0);
}

//mygets1.h - - -  my gets function 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* mygets(char str[]); //func prototype

char* mygets(char str[])

{
    //    char *str;
    unsigned int i = 0;
    int bffr_fl = 1; //flag to check the if user input exceeds 4 chars
    int mul_factor = 1; //how many 16-char wide chunks do we need?
    int tmp; //holder for the multiplication (see below)
    size_t sze = strlen(str);

    while ((str[i] = getchar()) != '\n'){
        i++;
        if(i >= sze && bffr_fl) {
                str = realloc(str,16*sizeof(char));//increase the size to 16
                bffr_fl = 0;
                mul_factor++;
        }
        else if(i % 16 == 0) {
           tmp = 16*mul_factor;         
-->       str = realloc(str,tmp*sizeof(char));//add another 16-wide chunk  to the tail
            mul_factor++;
        }
    }
    printf("the user pressed enter at position number %d\n",i);
    str[i] = '\0'; //append a trailing null after the last char
    return str;
}

Hope to hear from you soon,

BR,
__________________
Hope to hear from you guys!

--------------------------------------------------

Best Regards,
Aijaz Baig.
  #2  
Old 01-Feb-2008, 09:12
fakepoo fakepoo is offline
Regular Member
 
Join Date: Oct 2007
Posts: 534
fakepoo is a jewel in the roughfakepoo is a jewel in the roughfakepoo is a jewel in the rough

Re: Segmentation fault issues with 'realloc'


The first parameter that you must pass realloc() needs to be a pointer to memory that was allocated with malloc/calloc/realloc. Not a memory location on the stack. See realloc for details.
  #3  
Old 01-Feb-2008, 11:27
aijazbaig1's Avatar
aijazbaig1 aijazbaig1 is offline
Member
 
Join Date: May 2006
Location: Sweden
Posts: 141
aijazbaig1 has a spectacular aura about

Re: Segmentation fault issues with 'realloc'


thnks for the reply,
what would one do if one needs to call realloc iteratively over a couple of times?.

Is it allowed in that case...?
__________________
Hope to hear from you guys!

--------------------------------------------------

Best Regards,
Aijaz Baig.
  #4  
Old 01-Feb-2008, 15:10
fakepoo fakepoo is offline
Regular Member
 
Join Date: Oct 2007
Posts: 534
fakepoo is a jewel in the roughfakepoo is a jewel in the roughfakepoo is a jewel in the rough

Re: Segmentation fault issues with 'realloc'


I would change the function signature to not take any parameters and make sure the calling program will always free the memory returned. For instance:

CPP / C++ / C Code:
// Note: Calling function must free memory
char* mygets()
{ char *result = NULL;
  
  //result = (char*)realloc()....do whatever you would do here

  // return result;
}


int main()
{ char *line = mygets();
  
  // do what you need to do with the line
  
  // free the line
  free(line);

  return 0;
}


There could be other options as well, like passing a pointer to memory and an integer of the amount of memory available. This would work similar to fgets() and could be ideal so that the calling program does not have to free() any memory it did not create. Then, though, you could just call fgets() and pass it stdin as the FILE* argument.
 
 

Recent GIDBlogUS Elections and the ?Voter?s Responsibility? by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
An Access Violation Segmentation Fault boschow C++ Forum 3 31-Jan-2008 14:34
segmentation fault error vermin1302 C Programming Language 7 25-Feb-2006 14:38
segmentation fault? in C micheldenostra C Programming Language 1 10-Sep-2005 13:27
Please help segmentation fault problem robsmith C Programming Language 1 08-May-2005 21:34
segmentation fault in c++ rushman8282 C++ Forum 2 26-Jan-2005 04:38

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 07:05.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.