【问题标题】:Probably wrong use of memory-Segmentation fault可能是内存使用错误——Segmentation fault
【发布时间】:2016-12-30 18:02:43
【问题描述】:

当我分配给整数“数字”的第一个值被分配给 R 数组时,我的程序崩溃了。它可能与我创建的指针有关,我似乎无法找到问题所在。如果我省略这部分代码:

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

,程序运行良好,即使它给出不同的输出。下面是代码:

#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]);
        }

} 

谢谢。

【问题讨论】:

  • R=(int *)malloc(n*sizeof(int)); 移动到scanf("%d", &amp;n); 之后。
  • 您正在使用未初始化的变量n 分配数组R
  • 好吧,非常感谢,请原谅我因为我的笨拙而提出这样的问题。
  • else-block 也是错误的。
  • 哪里不对?

标签: c segmentation-fault


【解决方案1】:
int i,n,number,temp,j,k=0,l,temp2;
int *R;

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

n 有什么价值?它是未初始化的,所以你用 C 语言调用 undefined behavior。任何事情都可能发生,崩溃是一回事。

【讨论】:

  • 谢谢!这确实是个问题。
  • @Achilles 太棒了。 Stack Overflow 的下一步是通过单击左侧的绿色复选标记接受对您最有帮助的答案。这将为您赢得一些积分。
猜你喜欢
  • 2018-08-15
  • 1970-01-01
  • 2011-06-30
  • 1970-01-01
  • 2016-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多