[英]Why does this code in C crash? (with pointers)
這是我的C類的練習,其中用戶輸入兩個整數a
和b
並且我必須創建一個函數,該函數返回包含a
和b
之間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;
}
此外,此函數完全不會更改指針本身。 它只是返回已傳遞給它的指針。 您寫道, “必須創建一個返回包含a
到b
之間所有整數的數組的函數” ,但是您的函數不會創建任何數組,它只是將值分配給傳遞給它的數組元素。
還要注意, 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.