Realloc Fail

This is a discussion on Realloc Fail within the C Programming forums, part of the General Programming Boards category; Hi everyone, i have been trying to make a function that receives a string if the form of characters and ...

  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    3

    Realloc Fail

    Hi everyone,
    i have been trying to make a function that receives a string if the form of characters and dynamically allocates memory for every subsequent character, the function itself works fine, as long as i try to do it for only one variable (char * type), when i try to use twice(for two variables) it corrupts them both and gives a memory error

    using visual studio 2008 or 2010

    Code:
    #include <stdio.h>
    #include <conio.h>
    #include <stdlib.h>
    
    void string_realloc(char* str);
    int main()
    {
    	/*dynalloc_req1*/char *str;
    	                 char *str2;
        /*dynalloc_req2*/
    					 
    	str=(char*)malloc(2);
            str2=(char*)malloc(2);
            if(str==NULL)
    		{printf("strfail");getch();return 0;}
    	if(str2==NULL)
    	       {printf("str2fail");getch();return 0;}				 
    	printf("Enter a string to compress: \n");
    	string_realloc(str);
            printf("Enter a string to compress: \n");
    	string_realloc(str2);
    	printf("%s",str);
    	printf("%s",str2);
            free(str);
    	free(str2);
    	getch();
    
    	return 0;
    }
    
    void string_realloc(char* str)
    {
    	int i;  //string index counter
    	char c; //temp storage for input char
    
    	for(i=0;(c=getchar())!='\n';i++)   
    	//stop condition is user "enter"
    	{
    		str[i]=c;
    		if ((str=(char*)realloc(str,i+2))==NULL)  
    		  {//alloc fail msg 
    		   printf("\n\nallocation failed, not enough memory");
    		   free(str);
    			 return;
    		  }         
    	}
    	str[i]='\0';//close the string
    }
    Attached Files Attached Files
    Last edited by Tolq; 06-16-2011 at 08:21 AM. Reason: inline the code

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    1) Please post your code in the open using code tags.

    2) A C program cannot have 2 functions with the same name.

    3) You need to look up the correct usage of strcmp().

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    3
    it seems you misunderstood me, i have only one function, but when i uncomment all commented code and call it twice for different strings it results in memory errors, and i have no intention to compare the strings, i just want to receive both of them by dynamic allocation

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    You can't use strcmp as a variable name, since it's a library function, if that's what you're asking. Pick a different name.

  5. #5
    Registered User
    Join Date
    Jun 2011
    Posts
    3
    my bad, renamed the variable, problem presists

  6. #6
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,439
    You're going to get a problem when realloc MOVES the memory to another area of memory, because the current one cannot be expanded.

    When this happens, you need to return the modified pointer back to main.

    Look at realloc, it is
    newpointer = realloc( oldpointer, newsize );

    Now look at your function.
    void string_realloc(char* str)

    This needs to follow the same style, that is, return a pointer to the (possibly moved) block of memory containing your string.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  7. #7
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,682
    From the code it seems that your realloc the pointer str inside the function. But to the str_realloc function you just send the value of str. But that wouldn't work, as your're changing the pointer 'str' inside the str_realloc function to point to a newly allocated block. You will have to look into the concept called pointer-to-pointer. Where you do something similar to follow

    Code:
    int main( void )
    {
        char *str = malloc( sizeof *str * 10 );
        .
        .
        str_realloc( &str ); free( str );
        return 0;
    
    }
    
    void str_realloc( char **str  )
    {
         char *temp; 
         
         if( ( temp = realloc( *str,  strlen( *str ) * 10 ) ) == NULL )
         {
             printf("realloc fail");
             return;
         }
         *str = temp;
    }
    Thats is just a sample code on how to use pointer-to-pointer. And also you can check how I use the realloc function. In your case, the new allocated memeory block is never been initialied to the original pointer str in main. As de-referening str in main after str_realloc is undefined.

    PS: I've skipped out few error checking which i shall leave it to you to do so. And also your code indentation is very poor. You will have to start indenting your code properly, or your bound to get no much help.

    ssharish
    Last edited by ssharish2005; 06-16-2011 at 05:43 PM. Reason: printf corrected
    Life is like riding a bicycle. To keep your balance you must keep moving - Einstein

  8. #8
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Quote Originally Posted by ssharish2005 View Post
    From the code it seems that your realloc the pointer str inside the function. But to the str_realloc function you just send the value of str. But that wouldn't work, as your're changing the pointer 'str' inside the str_realloc function to point to a newly allocated block. You will have to look into the concept called pointer-to-pointer. Where you do something similar to follow

    Code:
    int main( void )
    {
        char *str = malloc( sizeof *str * 10 );
        .
        .
        str_realloc( &str ); free( str );
        return 0;
    
    }
    
    void str_realloc( char **str  )
    {
         char *temp; 
         
         if( ( temp = realloc( *str,  strlen( *str ) * 10 ) ) == NULL )
         {
             print "realloc fail";
             return;
         }
         *str = temp;
    }
    Thats is just a sample code on how to use pointer-to-pointer. And also you can check how I use the realloc function. In your case, the new allocated memeory block is never been initialied to the original pointer str in main. As de-referening str in main after str_realloc is undefined.

    PS: I've skipped out few error checking which i shall leave it to you to do so. And also your code indentation is very poor. You will start indenting your properly, or you gte no much help.

    ssharish
    Love your print function ssharish , that should really be part of the standard no pun intended.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  9. #9
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,682
    >Love your print function ssharish , that should really be part of the standard no pun intended.
    haha my typo. Yeah we could perhaps macro it!!!

    ssharish
    Life is like riding a bicycle. To keep your balance you must keep moving - Einstein

  10. #10
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by ssharish2005 View Post
    Code:
    int main( void )
    {
        char *str = malloc( sizeof *str * 10 );
        .
        .
        str_realloc( &str ); free( str );
        return 0;
    
    }
    
    void str_realloc( char **str  )
    {
         char *temp; 
         
         if( ( temp = realloc( *str,  strlen( *str ) * 10 ) ) == NULL )
         {
             printf ("realloc fail");  
             return;
         }
         *str = temp;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opendir fail
    By eyal_lesh in forum C Programming
    Replies: 2
    Last Post: 06-07-2011, 02:32 AM
  2. fail to count digit of an integer (fail at 9)
    By azsquall in forum C++ Programming
    Replies: 3
    Last Post: 05-02-2008, 09:42 AM
  3. Why does this fail?
    By kryonik in forum C++ Programming
    Replies: 8
    Last Post: 04-08-2006, 03:09 PM
  4. cin.fail
    By bj31t in forum C++ Programming
    Replies: 3
    Last Post: 04-01-2004, 02:26 PM
  5. help with cin.fail()
    By volk in forum C++ Programming
    Replies: 6
    Last Post: 04-02-2003, 02:32 PM

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