Thread: program crashes, no idea why

  1. #1
    Registered User
    Join Date
    Nov 2017
    Posts
    2

    program crashes, no idea why

    this is the source code, the compiler(myngw,gcc) doesnt warn me about anything, but when i start the program it crashes.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
     
    int matrixmax(int height,int width,int** tomb){
        int i,j,max=0;
        for(i=0;i<height;i++){
               for(j=0;i<width;j++){
                if(tomb[i][j]>max){
                    max=tomb[i][j];
                }           
           }
       }
       return max;
    }
    
    
    int main() {
       int i,j,height=2,width=3;
       int** tomb;
       tomb=malloc(height*sizeof(int*));
       for(i=0;i<height;i++){
               tomb[i]=malloc(width*sizeof(int));
    
    
       }
       for(i=0;i<height;i++){
           for(j=0;j<width;j++){
               tomb[i][j]=rand()%100+1;
           }
       }
    
    
        printf("%d",matrixmax(height,width,tomb));
    
    
    
    
       for(i=0;i<height;i++){
           free(tomb[i]);
       }
       free(tomb);
    
    
    }
    the program allocates some memory for a 2d array, and then a function finds the max value and returns it.

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Well here is the problem:
    Code:
    (gdb) run
    Starting program: C:\Users\jk\Desktop\sandbox.exe
    [New Thread 11136.0x15f0]
    [New Thread 11136.0x187c]
    
    Program received signal SIGSEGV, Segmentation fault.
    0x00000000004015ff in matrixmax (height=2, width=3, tomb=0xb61640)
        at sandbox.c:8
    8                   if(tomb[i][j]>max){
    (gdb) print i
    $1 = 0
    (gdb) print j
    $2 = 3680
    See how j is really big? That means that the matrix is trying to access memory it doesn't own. It can cause a segmentation fault.

    As for why j is really big, look carefully at the inner loop in matrixmax().
    Code:
     for(j=0;i<width;j++){
    You probably meant j < width. What you have written makes the loop work very differently.

  3. #3
    Registered User
    Join Date
    Nov 2017
    Posts
    2
    Indeed, didnt notice that at all.
    Thanks for the fast response!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Program crashes at the end of the job.
    By MartinR in forum C Programming
    Replies: 4
    Last Post: 02-22-2014, 12:30 PM
  2. Program Crashes
    By astroboy739 in forum C Programming
    Replies: 11
    Last Post: 08-20-2012, 06:21 AM
  3. Odd program crashes
    By Mithoric in forum Windows Programming
    Replies: 3
    Last Post: 03-20-2004, 11:37 PM
  4. Program crashes
    By fkheng in forum C Programming
    Replies: 12
    Last Post: 06-24-2003, 04:59 AM
  5. program crashes
    By Strut in forum Linux Programming
    Replies: 3
    Last Post: 02-10-2002, 10:49 AM

Tags for this Thread