繁体   English   中英

为什么此代码在C中崩溃? (带指针)

[英]Why does this code in C crash? (with pointers)

这是我的C类的练习,其中用户输入两个整数ab并且我必须创建一个函数,该函数返回包含ab之间a所有整数的数组:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int* arrayfromatob(int a,int b,int *p)
{
     int i;
     for(i=0;i<=b-a+1;i++)
            p[i]=a+i;
     return p;
} 

main()
{
      int a,b,*p,i,temp;
      puts("Give two integers:");
      scanf("%d %d",&a,&b);
      if(b<a)
      {
             temp=a;
             a=b;
             b=temp;
      }
      p=(int*)calloc(b-a+1,sizeof(int));
      if(p==NULL)
      {
                 puts("Could not allocate memory");
                 exit(1);
      }
      p=arrayfromatob(a,b,p);
      for(i=0;i<b-a+1;i++)
                printf("Number %d: %d\n",i+1,p[i]);
      free(p);
      system("pause");
}

为什么此代码崩溃? (我认为这与free(p);有关,但我不确定...)

    for(i=0;i<=b-a+1;i++)
        p[i]=a+i;

您正在访问b - a + 2元素。 但是您在以下位置分配了b - a + 1元素:

p=(int*)calloc(b-a+1,sizeof(int));

以下循环经过数组的末尾:

 for(i=0;i<=b-a+1;i++)

arrayfromatob函数中for循环的最后一次迭代尝试访问p[b-a+1] ,这超出了范围,因此产生了未定义的行为

int* arrayfromatob(int a,int b,int *p)
{
    int i;
    for(i=0;i<=b-a+1;i++)   // <-- b-a+2 iterations
        p[i]=a+i;
    return p;
} 

此外,此函数完全不会更改指针本身。 它只是返回已传递给它的指针。 您写道, “必须创建一个返回包含ab之间所有整数的数组的函数” ,但是您的函数不会创建任何数组,它只是将值分配给传递给它的数组元素。

还要注意, calloc零初始化所分配的内存,无论如何您都将要重写它。 简单的malloc就足够了。 这是函数的实际外观:

// returns the pointer to the newly-created array
// caller should free() this pointer when he's done with it
int* arrayfromatob(int a, int b)
{
    int i, size;
    size = b - a + 1;
    int* p = malloc(size * sizeof(int));
    for (i = 0; i < size; i++)
        p[i] = a + i;
    return p;
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM