Marwan Tushyeh
Marwan Tushyeh

Reputation: 1525

segmentation fault when executing C code in ubuntu

When I compile the c file, gcc returns no errors, but a segmentation fault occurs at runtime. The debugger showed that the fault occurs in this part of the code:

      int q=size[current];
      int *temp;
      temp = malloc ( sizeof(int)*q);
      for(i=0;i<size[current];i++)
        temp[i]=arr[current][i];

arr is defined :

      int arr[20][200];

current by default is 0.

I am trying to copy the contents of an array inside the 2d array (arr) to a temporary array, I've tried not using malloc but still the same problem.

ps: the program runs fine on windows.

Upvotes: 2

Views: 2395

Answers (2)

user1123450
user1123450

Reputation: 86

I suspect that size[current] is greater than 200.

Upvotes: 2

Employed Russian
Employed Russian

Reputation: 213955

There is nothing wrong with the code you have shown (that I can see).

The first step you should take is run your program under Valgrind, and fix any errors it reports.

If Valgrind reports errors you don't understand, update your question with Valgrind output.

If Valgrind does not report anything, run your program under GDB, print values of i, current, size[current], etc. and update your question with your GDB session.

Upvotes: 3

Related Questions