Thread: malloc and realloc Help

  1. #1
    Registered User
    Join Date
    Dec 2014
    Posts
    12

    malloc and realloc Help

    I'm struggling with using malloc() and realloc() in a program I'm using. I need to allocate space for a 2 dimensional array which has size a x 2 where a is a number that I won't know until near the end of my program. I need to start by making an array, call it matrix, of size matrix[1][2]. Then I will go into a for loop and if the program gets through the first iteration without some things happening (a collision of two masses specifically but I won't go into detail) then I want the array to have size matrix[2][2], if it gets through the next iteration then it should have size matrix[3][2] etc.

    I have written this code to try and work out how the malloc and realloc functions work and it compiles but when I try to run it I get "bus error".

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main(int argc, char *argv[])
    {
        double** matrix;
        
        matrix = malloc(sizeof(double*)*2);
        matrix[0] = malloc(sizeof(double));
        matrix[1] = malloc(sizeof(double));
        
        int i;
        
        for (i=2; i<=10; i++)
        {
            matrix[0] = realloc(matrix, sizeof(double)*i);
            matrix[1] = realloc(matrix, sizeof(double)*i);
        }
        
        for (i=0; i<10; i++)
        {
            matrix[i][0] = i;
            matrix[i][1] = i;
        }
        
        for (i=0; i<10; i++)
        {
            printf ("| %.1lf %.1lf |\n",matrix[i][0],matrix[i][1]);
        }
        
        return(0);
    }
    I'm fairly new to programming and so I'll likely be making some trivial errors but I can't work out what they are.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    > matrix[0] = realloc(matrix, sizeof(double)*i);
    If should be
    Code:
    void *p = realloc( matrix[0], sizeof(double)*i);
    if ( p != NULL ) {
      matrix[0] = p;
    } else {
      // oops - cleanup?
      free( matrix[0] );
    }
    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.

  3. #3
    Registered User
    Join Date
    Dec 2014
    Posts
    12
    This new code now leaves me with a segmentation fault.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main(int argc, char *argv[])
    {
    	double** matrix;
    	
    	matrix = malloc(sizeof(double*)*2);
    	matrix[0] = malloc(sizeof(double));
    	matrix[1] = malloc(sizeof(double));
    	
    	int i;
    	
    	for (i=2; i<=10; i++)
    	{
    		void *p = realloc( matrix[0], sizeof(double)*i);
    		if ( p != NULL ) {
    		  matrix[0] = p;
    		} else {
    		  // oops - cleanup?
    		  free( matrix[0] );
    		}
    		
    		void *q = realloc( matrix[1], sizeof(double)*i);
    		if ( q != NULL ) {
    		  matrix[1] = q;
    		} else {
    		  // oops - cleanup?
    		  free( matrix[1] );
    		}
    	}
    	
    	for (i=0; i<10; i++)
    	{
    		matrix[i][0] = i;
    		matrix[i][1] = i;
    	}
    		
    	for (i=0; i<10; i++)
    	{
    		printf ("| %.1lf %.1lf |\n",matrix[i][0],matrix[i][1]);
    	}
    	
    	return(0);
    }
    Also, I don't understand that fully. Why would p be null? Why do you need to have the free( matrix[0] ) bit?

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    In the two for loops, after the one using realloc(), the array indices are being used in the wrong order. For example, where you use matrix[i][0], you need matrix[0][i].
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  5. #5
    Registered User
    Join Date
    Dec 2014
    Posts
    12
    Yes but now I get

    Code:
    primrose > ./malloctest
    | 0.0 1.0 |
    | 0.0 1.0 |
    Segmentation fault

  6. #6
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Then you haven't fixed every instance of the problem I pointed out.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  7. #7
    Registered User
    Join Date
    Nov 2014
    Location
    Centurion, Gauteng, South Africa
    Posts
    28
    Something I can answer! omg im giddy! XD

    if you do something like malloc or realloc there is a chance you might not have enough memory available to be allocated. Basically you want a setup like this :

    Code:
    void *p;
    p = realloc . . . // strut your stuff
    if ( p != NULL ) 
    {
    //Do whatever  you intended to do
    StrokeKitty(3);
    free(p);
    //free the memory you used so the operating system can use it again.
    //I'm not sure about this but if I remember correctly you only free memory that was allocated successfully
    //Makes sense no?
    }
    else 
    {
    //Break or something from the function because well you didn't get
    //that memory from the os. darn. 
    //Fml right?
    }
    The same goes for malloc and calloc. I want to throw something about the stack in here but I'm too afraid Salem , Grumpy or laserlight will prove me wrong :/

    As for free , you call free to release the memory that you've been using. If you don't free the memory and your program keeps running ( a background process or something ) then well that memory won't be accessibile because you ( and your program which happens to never end ) never told the OS that it can have it's crap back now . I had a post somewhere. . .

    String Handling - Memory Leak?

    laserlight explains what I was doing wrongly. I think it might be the same as an assembly program that I wrote although in this particular example I was trying to see if I could force a stack overflow.

    Code:
    BITS 32
    extern __cprintf
    extern __getch
    extern _ExitProcess
    global main
    section .data
    StackGrowth dd 0
    StackState dd 0
    StackGrowthMessage db "Stack Growth -> %i",0ah,0
    CounterMessage db "Counter -> %i",0ah,0
    EspMessage db "ESP Register -> %i",0ah,0
    EbpMessage db "EBP Register -> %i",0ah,0
    ThreeNewLines db "",0ah,0ah,0ah,0
    ThreeNewLinesMessage db "%s",0
    Counter dd 0
    section .text
    main:
    mov dword [StackState],esp
    push ebp
    push EbpMessage
    call __cprintf
    add esp,8;2*4 bytes = 8
    
    
    push esp
    push EspMessage
    call __cprintf
    add esp,8
    
    
    push dword [Counter]
    push CounterMessage
    call __cprintf
    
    
    add esp,8
    ;call __getch
    
    
    push ThreeNewLines
    push ThreeNewLinesMessage
    call __cprintf
    
    
    add esp,8 ;If this op is not defined a stack overflow will occur
    
    
    
    
    
    
    
    
    
    
    cmp [Counter],dword 1000000000
    je exit
    jmp Increment
    
    
    
    
    
    
    exit:
    push 0
    call _ExitProcess
    
    
    
    
    Increment:
    add [Counter],dword 1
    ; INVALID : mov [StackGrowth],[StackState]
    mov ebx,[StackState]
    mov [StackGrowth],ebx
    mov ebx,esp
    sub ebx,[StackGrowth]
    mov [StackGrowth],ebx
    neg dword [StackGrowth]
    push dword [StackGrowth]
    push StackGrowthMessage
    call __cprintf
    add esp,8
    JMP main
    I couldnt upload the exe but thats fine. It really just was for the fun of it.

    I just know someone's going to jump me on this but feel free to do so. Basically what happens here is I was pushing values to the stack (which is kind of like allocating memory ) but I wasn't popping them / changing the esp register accordingly (which is kind of like free ) which results in a stack overflow ( think of a tower that keeps getting higher and higher until finally well lots of people are dead - OK SO THE STACK UUUUSUUAAALLY GROWS DOWNWARDS THATS NOT REALLY THE POINT XD - ).

    I really did try on this post I swear I tried
    Last edited by RagingGrim; 12-23-2014 at 12:33 PM. Reason: I TRIED! :( ; The Tower THingy.

  8. #8
    Registered User
    Join Date
    Nov 2014
    Location
    Centurion, Gauteng, South Africa
    Posts
    28
    I looked at your coding ( for the first time XD ) and realised that you were freeing the NULL pointer ; That is incorrect because in practise generic pointers ( void pointers ) are set to NULL when they are not in use anymore.

    Also segmentation fault? I get that on my kali 1linux system using geany. It feels so amazing to code on linux but then again it's probably best if you stick to windows. Codeblocks using the gcc compiler works just fine Your error messages will be much much more helpful. Otherwise you could just keep inserting a puts("test") to see where the segmentation fault is occuring. That or breakpoints but my breakpoints never work :/

  9. #9
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by RagingGrim View Post
    I looked at your coding ( for the first time XD ) and realised that you were freeing the NULL pointer ; That is incorrect because in practise generic pointers ( void pointers ) are set to NULL when they are not in use anymore.
    Not true.

    1) realloc() can be supplied a NULL pointer. If it is, it just allocates memory (like malloc() would) or return NULL to indicate failure.

    2) Pointers, whether void or otherwise, are not set to NULL when not in use any more (e.g. after calling free()).
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  10. #10
    Registered User
    Join Date
    Nov 2014
    Location
    Centurion, Gauteng, South Africa
    Posts
    28
    I must have edited this three times.

    Sorry for the assumptions So calling free does not set the pointer to NULL?
    Is that why it's good practise to do this yourself after calling free?

    Thanks for the corrections though Grumpy ^^
    Last edited by RagingGrim; 12-23-2014 at 03:45 PM.

  11. #11
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    You're just tired.
    Code:
            void *p = realloc( matrix[0], sizeof(double)*i);
            if ( p != NULL ) {
              matrix[0] = p;
            } else {
              // oops - cleanup?
              free( matrix[0] );
            }
    If realloc() returns NULL, the allocation failed and matrix[0] is unmodified, so needs to be released. If realloc() returns something other than NULL, the allocation succeeded, and matrix[0] has been released (and cannot be released again). However, the new address has not been stored in matrix[0] so it is then necessary to store the result (p) into matrix[0].
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  12. #12
    Registered User
    Join Date
    Nov 2014
    Location
    Centurion, Gauteng, South Africa
    Posts
    28
    Quote Originally Posted by grumpy View Post
    You're just tired.
    I think I'll take this as a compliment my day has been made

    Thanks for the clarification

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Use of malloc and realloc
    By mrbains in forum C Programming
    Replies: 5
    Last Post: 11-11-2010, 02:53 AM
  2. malloc and realloc
    By jayfriend in forum C Programming
    Replies: 4
    Last Post: 01-05-2007, 02:25 PM
  3. malloc, realloc
    By figo2476 in forum C Programming
    Replies: 3
    Last Post: 04-28-2006, 10:11 PM
  4. malloc and realloc
    By odysseus.lost in forum C Programming
    Replies: 3
    Last Post: 05-27-2005, 08:44 AM
  5. malloc and realloc
    By C-Struggler in forum C Programming
    Replies: 2
    Last Post: 03-11-2003, 11:31 AM