2016-04-29 8 views
-4

malloc関数を使用するcでプログラムを作成しました。 コード: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); 
} 

それは運によって可能である....それは10個の整数が10バイトに格納されていることが可能である.How 10バイトのメモリを割り当てること

+0

整数は通常4バイトとなり、境界から書き出します – Pooya

+2

*「10個の整数が10バイトにどのように格納されるのか」.... *そうではありません。 –

+1

データ型のサイズを追加する必要があります: 'ptr = malloc(sizeof(int)* n);' – jboockmann

答えて

1

をmalloc関数を使用しています。

割り当てられた領域外に書き込むと、結果としてプログラムにUB(未定義動作)が発生します。

しかし、プログラムはいくつかの状況で動作するように見えるかもしれませんが、一般的にはいつでもクラッシュする可能性があります。