【问题标题】:Malloc function in c [duplicate]c中的Malloc函数[重复]
【发布时间】:2016-04-29 16:49:15
【问题描述】:

我用 c 语言编写了一个使用 malloc 函数的程序。 代码:

#include<stdio.h>
#include<stdbool.h>
#include<malloc.h>

int main(){
    int n;
    int *ptr,i,sum;
    sum = 0;
    printf("Enter the number = ");
    scanf("%d",&n);
    ptr = (int *)(malloc(10));
    for(i=0;i<n;i++){
        scanf("%d",ptr+i);
        sum += *(ptr+i);
    }
    printf("The sum of the numbers is = %i",sum);
}

我已经使用malloc函数分配了10个字节的内存。10个整数怎么可能存储在10个字节中......

【问题讨论】:

  • 整数通常占用 4 个字节,而您的写入超出范围
  • “10个整数怎么可能存储在10个字节中……”不是。
  • 你必须添加数据类型的大小:ptr = malloc(sizeof(int) * n);
  • 您的代码不会在 10 字节空间中存储 10 个整数。实际上,您也没有在 10 字节空间中存储任何 int。
  • @piling:但是是的,他做到了:scanf("%d",ptr+i);,写入超出数组的限制,如果 n 大于 2...

标签: c data-structures


【解决方案1】:

这是可能的运气。

您在分配的区域之外写入,因此您的程序具有 UB(未定义行为)。

但是,该程序在某些情况下似乎可以工作,但通常它可能随时崩溃。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 2017-12-06
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 2011-06-25
    相关资源
    最近更新 更多