Like Tree3Likes
  • 1 Post By grumpy
  • 2 Post By laserlight

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

This is a discussion on difficulty in using malloc for 2D array when outside the main function within the C Programming forums, part of the General Programming Boards category; HI please help me here. Segmentation fault always occur in my program. when malloc is in main, it is running, ...

  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
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,669
    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,265
    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.
    stahta01 likes this.
    Right 98% of the time, and don't care about the other 3%.

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,500
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  5. #5
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,302
    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,265
    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%.

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,652
    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.
    grumpy and stahta01 like this.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    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, 08: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, 04:19 PM

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