Thread: difficulty in using malloc for 2D array when outside the main function

  1. #1
    Registered User
    Join Date
    Jul 2011
    Posts
    2

    difficulty in using malloc for 2D array when outside the main function

    HI please help me here. Segmentation fault always occur in my program. when malloc is in main, it is running, but when i put malloc in another function, segmentation fault occurs. here is my code

    Code:
    #include<stdio.h>
    #include<malloc.h>
    
    void malloc_array(int **array;int row;int col){
    
    	int i;
    	
    	array=(int**)malloc(row*sizeof(int*));
    	for(i=0;i<row;i++){
    		array[i]=(int*)malloc(col*sizeof(int);
    	}
    }
    
    main(){
    	int **array, row=5, col=7;
    	
    	malloc_array(array,row,col);
    
          .
          .
          .
    }

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    You should be returning the array variable. You get the segmentation fault because you've leaked the memory allocated by malloc when this function returns, and the pointers are invalidated. Think about how malloc works. It also returns allocated pointers: when you roll your own allocation functions, they should behave the same way.

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    That code won't even compile, let alone give a segmentation fault. As a rough rule, it is better to post ACTUAL functional code in forums (for example, cut and paste from an actual source file) than it is to try to paraphase ot to type it in from memory. You have not posted actual code, so have mucked up, big time.

    However, if you want to pass a "pointer to pointer" to a function, and have any changes made visible to the caller, you have to pass a "pointer to pointer to pointer". For example (count the asterixes and ampersands carefully)
    Code:
    #include<stdio.h>
    #include<malloc.h>
    
    void malloc_array(int ***array,int row,int col)
    {
    	int i;
    	
    	*array=malloc(row*sizeof(int*));
    	for(i=0;i<row;i++){
    		(*array)[i]=malloc(col*sizeof(int));
    	}
    }
    
    int main()
    {
    	int **array, row=5, col=7;
    	
    	malloc_array(&array,row,col);
    
             /*   You can now use array here without getting in danger */
    }
    Incidentally, it is considered bad style to rely on the "implicit int" return type (and such things are deprecated). If a function returns int, write it that way. In C, you should not need to have a type conversion on the return value from malloc().
    Last edited by grumpy; 07-20-2011 at 05:10 AM.
    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.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Not to mention...

    void malloc_array(int ***array;int row;int col)
    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.

  5. #5
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Shouldn't the original code give a warning about an uninitialised variable?
    The pointer is being passed in by value but has never been made to point to anything.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  6. #6
    Registered User
    Join Date
    Jul 2011
    Posts
    2

    Smile

    Quote Originally Posted by grumpy View Post
    That code won't even compile, let alone give a segmentation fault. As a rough rule, it is better to post ACTUAL functional code in forums (for example, cut and paste from an actual source file) than it is to try to paraphase ot to type it in from memory. You have not posted actual code, so have mucked up, big time.

    However, if you want to pass a "pointer to pointer" to a function, and have any changes made visible to the caller, you have to pass a "pointer to pointer to pointer". For example (count the asterixes and ampersands carefully)
    Code:
    #include<stdio.h>
    #include<malloc.h>
    
    void malloc_array(int ***array,int row,int col)
    {
    	int i;
    	
    	*array=malloc(row*sizeof(int*));
    	for(i=0;i<row;i++){
    		(*array)[i]=malloc(col*sizeof(int));
    	}
    }
    
    int main()
    {
    	int **array, row=5, col=7;
    	
    	malloc_array(&array,row,col);
    
             /*   You can now use array here without getting in danger */
    }
    Incidentally, it is considered bad style to rely on the "implicit int" return type (and such things are deprecated). If a function returns int, write it that way. In C, you should not need to have a type conversion on the return value from malloc().
    thank you for your answer, this is my first post here so i am not really sure of what i'm doing. thank you.

  7. #7
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by iMalc View Post
    Shouldn't the original code give a warning about an uninitialised variable?
    The pointer is being passed in by value but has never been made to point to anything.
    There is no "should" (or "shouldn't") about it.

    Accessing the value of any uninitialised variable, according to the standard, gives undefined behaviour (and "pass by value" is so-named because it accessed the value in order to pass it). That means there is no requirement for a compiler diagnostic, no requirement for sensible runtime behaviour, no requirement for a run time error, and no requirement for anything else.

    In practice, warning about uninitialised variables is generally considered a quality-of-implementation concern for the compiler - as is anything normally categorised as a "warning". Good quality compilers are often able to detect and report cases of uninitialised variables. However, other than programmer expectations and willingness of vendors to satisfy them, there is no force that ensures any compiler will report uninitialised variables.

    Most compilers with capability to report uninitialised variables disable that feature by default. There are various reasons, both good and bad, for that state of affairs. It is therefore necessary, with those compilers, to activate higher levels of warning (for example, by command line switches).

    [Personally, I consider any programmer worth their salt will activate the maximum warning levels for every compiler they use]
    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.

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by grumpy
    However, if you want to pass a "pointer to pointer" to a function, and have any changes made visible to the caller, you have to pass a "pointer to pointer to pointer". For example (count the asterixes and ampersands carefully)
    Rather than be a three star programmer, consider wrapping your 2D array in a struct that could well include the row and col variables. Even if you do not ever pass a pointer to this struct to a function, it can still be helpful as an abstraction.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing array back to main function
    By greg677 in forum C Programming
    Replies: 11
    Last Post: 05-01-2010, 04:27 PM
  2. How to pass a matrix/array from main to a function
    By Inukami in forum C Programming
    Replies: 7
    Last Post: 12-09-2009, 09:03 PM
  3. Replies: 7
    Last Post: 10-15-2008, 03:38 AM
  4. Little Array Difficulty
    By G4B3 in forum C Programming
    Replies: 16
    Last Post: 03-19-2008, 12:59 AM
  5. Passing a double array from main to another function
    By Loctan in forum C++ Programming
    Replies: 2
    Last Post: 01-04-2005, 05:19 PM