realloc segfaults.

This is a discussion on realloc segfaults. within the C Programming forums, part of the General Programming Boards category; Code: #include <stdio.h> #include <stdlib.h> #include <string.h> struct StudentInfo{ unsigned int roll; }; typedef struct StudentInfo StdInfo; int main(int argc, ...

  1. #1
    Registered User
    Join Date
    Jun 2007
    Posts
    219

    realloc segfaults.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct StudentInfo{
            unsigned int roll;
    };
    
    typedef struct StudentInfo StdInfo;
    
    int main(int argc, char** argv){
            StdInfo* students;
            unsigned int size = 3, i=0, j;
            unsigned short int s = 1;
            char* dump_name;
    
            students = malloc( size*sizeof(StdInfo) );
    
            do{
                    printf("Enter Roll of Student %d :\t", i);
                    scanf("%d", &(students[i].roll));
                    printf("\n\nEnter another ? (1/0):\t");
                    scanf("%d", &s);
                    if(s == 1){
                            size *= 2;
                            students = realloc( students, size*sizeof(StdInfo) );
                    }
                    i++;
            }while(s == 1);
    
            free(students);
            students = 0x0;
    
            return 0;
    }
    Why does the above code Crashes. I suspect its caused by realloc But how to solve it ?

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Katy, Texas
    Posts
    2,309
    Under what conditions does it crash?
    Mac and Windows cross platform programmer. Ruby lover.

    Quote of the Day
    12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.

    Amen brother!

  3. #3
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,047
    Code:
    scanf("%d", &s);
    Last edited by itCbitC; 11-25-2008 at 09:33 AM. Reason: goofed not

  4. #4
    Registered User slingerland3g's Avatar
    Join Date
    Jan 2008
    Location
    Seattle
    Posts
    603
    You are needing to allocate room for each of your elements of the array. Also you should check the return on your realloc call for good measure.

  5. #5
    Registered User
    Join Date
    Jun 2007
    Posts
    219
    Quote Originally Posted by itCbitC View Post
    You are allocating storage for the pointer but not for the object it points to -> struct StudentInfo.
    Hmm after I did
    Code:
    StdInfo* students;
    I also did
    Code:
    students = malloc( size*sizeof(StdInfo) );
    initially storage for teh Object is also allocated.
    Quote Originally Posted by slingerland3g View Post
    You are needing to allocate room for each of your elements of the array. Also you should check the return on your realloc call for good measure.
    I am doing
    Code:
    students = realloc( students, size*sizeof(StdInfo) );
    What else I have to do to accomplish that you said ??

  6. #6
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,673
    Why are you doubling the size every time around the loop?
    As opposed to only when the memory you have so far is full.

    Also, do this
    Code:
    void *p = realloc( students, size*sizeof(StdInfo) );
    if ( p != NULL ) {
      students = p;
    } else {
      // students still points to the old memory
      // free it, save it, whatever
    }
    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
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Katy, Texas
    Posts
    2,309
    This operation makes no sense to me. Why does the value in students not take?

    Here's the code: (same as above with printfs)
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct StudentInfo{
            unsigned int roll;
    };
    
    typedef struct StudentInfo StdInfo;
    
    int main(int argc, char** argv){
            StdInfo* students;
            unsigned int size = 3, i=0 ;
            unsigned short int s = 1;
           // char* dump_name;
    
            students = malloc( size*sizeof(StdInfo) );
    		printf("students @ = &#37;p\n", students) ; 
    		printf("Size of StdInfo = %d\n", size*sizeof(StdInfo)) ; 
    		
            do{
                    printf("Enter Roll of Student %d :\t", i);
                    scanf("%d", &(students[i].roll));
                    printf("\n\nEnter another ? (1/0):\t");
                    scanf("%d", &s);
                    if(s == 1){
                            size *= 2;
    						printf("New Size of StdInfo = %d\n", size*sizeof(StdInfo)) ; 
                            printf("students @ %p being realloced...\n", students) ; 
    						students = realloc( students, size*sizeof(StdInfo) );
    						printf("students new @ = %p\n", students) ; 
                    }
                    i++;
            }while(s == 1);
    
            free(students);
            students = 0x0;
    
            return 0;
    }
    and here's the output. Note the original address of 0x100000 does not change!!

    Code:
    [Session started at 2008-11-25 10:40:40 -0600.]
    students @ = 0x100180
    Size of StdInfo = 12
    Enter Roll of Student 0 :	1
    
    
    Enter another ? (1/0):	1
    New Size of StdInfo = 24
    students @ 0x100000 being realloced...
    students new @ = 0x100000
    Enter Roll of Student 1 :	1
    
    
    Enter another ? (1/0):	1
    New Size of StdInfo = 48
    students @ 0x100000 being realloced...
    students new @ = 0x100150
    Enter Roll of Student 2 :	1
    
    
    Enter another ? (1/0):	1
    New Size of StdInfo = 96
    students @ 0x100000 being realloced...
    c_misc3(41686) malloc: *** error for object 0x100000: double free
    *** set a breakpoint in malloc_error_break to debug
    students new @ = 0x1001d0
    Enter Roll of Student 3 :	1
    
    
    Enter another ? (1/0):	1
    New Size of StdInfo = 192
    students @ 0x100000 being realloced...
    c_misc3(41686) malloc: *** error for object 0x100000: double free
    *** set a breakpoint in malloc_error_break to debug
    students new @ = 0x100230
    Enter Roll of Student 4 :
    Mac and Windows cross platform programmer. Ruby lover.

    Quote of the Day
    12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.

    Amen brother!

  8. #8
    Registered User
    Join Date
    Jun 2007
    Posts
    219
    Well this is my current code
    Code:
    	do{
    		printf("Enter Roll of Student %d :\t", i);
    		fflush(stdin);
    		scanf("%d", &(students[i].roll));
    		printf("\n\nEnter another ? (1/0):\t");
    		fflush(stdin);
    		scanf("%d", &s);
    		fflush(stdin);
    		if(s == 1){
    			size += 1;
    			void* dump = realloc( students, size*sizeof(StdInfo) );
    			if(dump != 0x0){
    				students = dump;
    			}else{
    				printf("realloc Failed\n");
    				return 2;
    			}
    		}
    		i++;
    	}while(s == 1);
    But it never stops after the first scanf for roll it doesn't scanf's any others and runs an infinite loop.

  9. #9
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Katy, Texas
    Posts
    2,309
    I figured it out, and itCbitC hit the nail on the head.
    Mac and Windows cross platform programmer. Ruby lover.

    Quote of the Day
    12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.

    Amen brother!

  10. #10
    Ex scientia vera
    Join Date
    Sep 2007
    Posts
    478
    You are on the right track, although flushing the input buffer is by definition undefined(Hur hur).

    Try this:

    Code:
    scanf("%d\n", &someInteger);
    Now scanf is waiting for a newline that it gets, so it reads it and then discards it as there is nothing to be done with it - no variable to put it on or anything similar. If I recall correctly, this should work.

    Alternatively, you could use fgets to read your data and thereafter strtol to convert it to an integer. It will effectively eradicate the annoying newline problem which is so persistent in C, but requires more code.
    "What's up, Doc?"
    "'Up' is a relative concept. It has no intrinsic value."

  11. #11
    Registered User
    Join Date
    Jun 2007
    Posts
    219
    tried just now
    Code:
    	do{
    		//StudentInfo.name removed
    
    		printf("Enter Roll of Student &#37;d :\t", i);
    		//fflush(stdin);
    		scanf("%d", &(students[i].roll));
    		printf("\n\nEnter another ? (1/0):\t");
    		//fflush(stdin);
    		scanf("%d\n", &s);
    		//fflush(stdin);
    		if(s == 1){
    			size += 1;
    			void* dump = realloc( students, size*sizeof(StdInfo) );
    			if(dump != 0x0){
    				students = dump;
    			}else{
    				printf("realloc Failed\n");
    				return 2;
    			}
    		}
    		i++;
    	}while(s == 1);
    No Change the same result

  12. #12
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Katy, Texas
    Posts
    2,309
    noobcpp - What is wrong with this?
    Code:
    scanf("&#37;d\n", &s);
    Mac and Windows cross platform programmer. Ruby lover.

    Quote of the Day
    12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.

    Amen brother!

  13. #13
    Registered User
    Join Date
    Jun 2007
    Posts
    219
    Quote Originally Posted by Dino View Post
    noobcpp - What is wrong with this?
    Code:
    scanf("&#37;d\n", &s);
    But I've already wrote scanf("%d\n", &s); in my code @ Line 9

    ----------- EDIT ---------

    did you mean this ??
    Code:
    		printf("Enter Roll of Student %d :\t", i);
    		//fflush(stdin);
    		int dmp_roll;
    		scanf("%d\n", &dmp_roll);
    		students[i].roll = dmp_roll;
    		printf("\n\nEnter another ? (1/0):\t");
    		//fflush(stdin);
    		scanf("%d\n", &s);
    THat doesn't solve the problem. its same.
    Last edited by noobcpp; 11-25-2008 at 11:08 AM.

  14. #14
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Katy, Texas
    Posts
    2,309
    Quote Originally Posted by noobcpp View Post
    But I've already wrote scanf("%d\n", &s); in my code @ Line 9

    ----------- EDIT ---------

    did you mean this ??
    Code:
    		printf("Enter Roll of Student %d :\t", i);
    		//fflush(stdin);
    		int dmp_roll;
    		scanf("%d\n", &dmp_roll);
    		students[i].roll = dmp_roll;
    		printf("\n\nEnter another ? (1/0):\t");
    		//fflush(stdin);
    		scanf("%d\n", &s);
    THat doesn't solve the problem. its same.
    I know you've written it, and it is wrong!! It is causing the problem. Figure out what is wrong with it.
    Mac and Windows cross platform programmer. Ruby lover.

    Quote of the Day
    12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.

    Amen brother!

  15. #15
    Registered User
    Join Date
    Jun 2007
    Posts
    219
    Quote Originally Posted by IceDane View Post
    You are on the right track, although flushing the input buffer is by definition undefined(Hur hur).

    Try this:

    Code:
    scanf("%d\n", &someInteger);
    I know you've written it, and it is wrong!! It is causing the problem. Figure out what is wrong with it.
    I am confused What would I write to solve this problem ??

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. did i understood right this explantion of realloc..
    By transgalactic2 in forum C Programming
    Replies: 3
    Last Post: 10-24-2008, 07:26 AM
  2. writing a pack-style function, any advices?
    By isaac_s in forum C Programming
    Replies: 10
    Last Post: 07-08-2006, 08:09 PM
  3. using realloc
    By bobthebullet990 in forum C Programming
    Replies: 14
    Last Post: 12-06-2005, 04:00 PM
  4. segfault on realloc
    By ziel in forum C Programming
    Replies: 5
    Last Post: 03-16-2003, 03:40 PM
  5. Realloc inappropriate for aligned blocks - Alternatives?
    By zeckensack in forum C Programming
    Replies: 2
    Last Post: 03-20-2002, 01:10 PM

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