Achilles
Achilles

Reputation: 29

Probably wrong use of memory-Segmentation fault

When the 1st value I've assigned to the integer "number" gets assigned to the R array, my program crashes. It probably has something to do with the pointer I've created and I do not seem to be able to find what is the problem. If I omit this part of the code:

else{
    while (k<=n/2){
        temp2=R[k];
        R[l-1]=temp2;
        R[k]=R[l-1];}
        l-=1;
        k+=1;
    }

, the program runs fine, even though it gives a different output. Below is the code:

#include <stdio.h>

main(){
    int i,n,number,temp,j,k=0,l,temp2;
    int *R;

    R=(int *)malloc(n*sizeof(int));

    printf("Dwse mou to megethos tou pinaka se parakalw poly:\n");
    scanf("%d", &n);
    for(i=0; i<n; i++){
            printf("Dwse enan thetiko akeraio arithmo:\n");
            scanf("%d", &number);
            R[i]=number;
    }
    for(i=1;i<n;i++){
        temp=R[i];
        j=i-1;
        while((temp>R[j])&&(j>=0)){
            R[j+1]=R[j];
            j=j-1;
      }
        R[j+1]=temp;
  }
    l=n;
    if (n%2==0)
        printf("Einai adynato na ginei h taksinomhsh:\n");
    else{
        while (k<=n/2){
            temp2=R[k];
            R[l-1]=temp2;
            R[k]=R[l-1];}
            l-=1;
            k+=1;
        }
    for(i=0; i<n; i++){
            printf("R[%d]: %d\n", i, R[i]);
        }

} 

Thank you.

Upvotes: 0

Views: 37

Answers (1)

Jens
Jens

Reputation: 72629

int i,n,number,temp,j,k=0,l,temp2;
int *R;

R=(int *)malloc(n*sizeof(int));

What value does n have? It's uninitialized, so you invoke undefined behavior in C lingo. Anything may happen, and a crash is one thing.

Upvotes: 2

Related Questions