1

I am new in C and i am creating a simple program in which i am writing value to the multidimensional error .But I am getting error "Segmentation fault" or some time when i am running the code it is getting in Infinite loop.

int main(){
int i,j;
int num1=10; 
int num2=10; 
double data[num1][num2];


    for(i=0;i<=num1;i++){
        for(j=0;j<=num2;j++){
            if(i==0) {
                data[i][j]=121.21;
            }
            else {
                data[i][j]=0.0;
            }
        }
    }
}

When i am doing the hardcoding of values on below structure it is working fine : change double data[num1][num2]; to double data[10][10];

How can we fix this issue in C.

2 Answers 2

5

You're overrunning the bounds of the array in your loops:

for(i=0;i<=num1;i++){
    for(j=0;j<=num2;j++){

In the outer loop i ranges from 0 to num1, while in the inner loop j ranges from 0 to num2. However, the maximum valid index for each array dimension is num1-1 and num2-1 respectively. Reading / writing past the end of an array invokes undefined behavior, which is why it sometimes worked and sometimes didn't.

Change the loop conditions to <:

for(i=0;i<num1;i++){
    for(j=0;j<num2;j++){
Sign up to request clarification or add additional context in comments.

Comments

0

It seems you are going over the memory the program is allowing you to access. You are allocating memory for 100 values (10*10). However, when dealing with arrays in most programming languages, it is important that you know index 0 counts as one such that you can go from array[0] - array[9] and that is declaring an array with memory for 10 spots since we start at 0 in most programming languages.

A clean way to fix this code would be:

for (int i=0; i < num1; i++) {
    for (int j=0; j < num2; j++ {

This would avoid accessing memory location at index 10 which is not allocated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.