不明白为什么我得到异常抛出错误

时间:2018-04-20 13:08:49

标签: c

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

int* createArr(int len);
/*
Convantional problem in Code:
There is no descreption to main.
Bugs:
1.line 32 - in scanf there is no & to the variable that'll stor the user input, scanf("%d,size") -> scanf("%d,&size")
2.line 33 - should be getchar(); and then the rest of the code. 
3.In createArr:
    1)line 48 - the parameters that malloc is getting is wrong - the function needs the total amout of bytes, so for int you need to mul the inputed amount by 4
      and the casting is to int and not a int type pointer. int * pArr = (int*)malloc(size) -> int * pArr = (int)malloc(sizeof(int) * size).
    2)line - in scanf() the storing variable is wrong,the storing variable should be the index in the array, scanf("%d",size) -> scanf("%d",*(arr + i)). (Another thing is that you didnt use & for the integer size)
    3)line 54 - should be getchar() after scanf() and then the rest of the code.
    4)line 57 - using the function free() in the wrong way, the function is realising spesific places in the computer memory and the function is used only when you dont need the memory the you allocated your self to the array.


*/
int main(void)
{
    int size = 0;
    int* pArr = 0;

    printf("Enter a number of cells: ");
    scanf("%d",&size);
    getchar();
    pArr = createArr(size);
    printf("The array is at address %p: ", pArr);
    free(pArr);
    getchar();
    return 0;
}

/*
Function creates an array
input: number of cells in the array
output: pointer to the new array
*/
int* createArr(int size)
{
    int * pArr = (int)malloc(sizeof(int) * size);
    int i = 0;
    for(i = 0; i < size; i++)
    {
        printf("Please enter a number for index %d: ",i);
        scanf("%d",*(pArr + i));
        getchar();
    }
    return pArr;
}

代码是我在课堂上的作业,我需要在代码中找到错误修复它们并解释它们。

问题: 当我执行代码时,我得到以下错误: 在q5.exe中0x0FE98E2E(ucrtbased.dll)抛出异常:0xC0000005:访问冲突写入位置0xCDCDCDCD。发生

使用断点后,我发现问题出现在这部分代码中:

int i = 0;
for(i = 0; i < size; i++)
{
    printf("Please enter a number for index %d: ",i);
    scanf("%d",*(pArr + i));
    getchar();
}

函数creatArr

我想了解为什么我会收到此错误,以便我可以修复它。

3 个答案:

答案 0 :(得分:1)

如果您不使用难以阅读的指针算术语法*(pArr + i),而是使用索引pArr[i],则错误更容易被发现。

scanf需要一个地址但你传递了一个值。将代码更改为:

scanf("%d", &pArr[i]);

也永远不会施放malloc的结果,因为这会隐藏bug。在您的情况下,它创建了一个新的错误,因为您不小心强制转换为int。您的编译器必须在那里给出诊断消息。

答案 1 :(得分:1)

拖出重大错误。

来自malloc的返回结果是void*不要将其投放到int(不要将其投射或至少将其投射到int*)。< / p>

*(pArr + i)这是取消引用指针。 scanf需要一个指针,在你的情况下,你给的是int。 您可以删除&#39; *&#39;和括号甚至更好,使用&pArr[i]

答案 2 :(得分:1)

这里有两个问题:

触发你提到的错误的是:

scanf("%d",*(pArr + i));

对于scanf,您需要将指针提供给您希望输入的变量,但是您提供了变量的

你需要

scanf("%d", pArr + i);

scanf("%d", &pArr[i]);

第二个问题更微妙:

在这一行中,您将malloc的结果转换为int,但您可能希望将其转换为int*malloc返回指针)。

int * pArr = (int)malloc(sizeof(int) * size);

但无论如何,在C中你不会从malloc投出返回值,只需写下:

int * pArr = malloc(sizeof(int) * size);

但最佳做法是写作:

int * pArr = malloc(sizeof *pArr * size);

这样sizeof的参数总是匹配类型的大小(int)。