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

int main ()
{
    int a,n;
    int * ptr_data;


    printf ("Enter amount: ");
    scanf ("%d",&a);
    int arr[a];
    ptr_data = (int*) malloc ( sizeof(int) );
    for ( n=0; n<a; n++ )
    {
        printf ("Enter number #%d: ",n);
        scanf ("%d",&ptr_data[n]);
    }

    for ( n=0; n<a; n++ )
        arr[n] = ptr_data[n]; //values in heap are copied to an array.
    printf("%d\n",sizeof(ptr_data));
    free (ptr_data);
    printf ("Output: ");
    for ( n=0; n<a; n++ )
        printf("%d\n",arr[n]);
    return 0;
}

the sizeof function prints the size of pointer as 4(integer's size). but i run a loop to get the values to be stored in the heap (scanf,.), so how does this subsequent pointee pointer mapping happens after first time? as in, first time i explicitly code that the ptr_data to contain a size of 4. but after that when i want to store another integer this pointer shows another random memory refernce(this mapping explanation is what all i want.)

trincot
  • 317,000
  • 35
  • 244
  • 286
bks4line
  • 485
  • 3
  • 10
  • 23

2 Answers2

1

What you have in your code is an Undefined behavior.

 ptr_data = (int*) malloc ( sizeof(int) );

Allocates memory equivalent to size of a single integer on heap and ptr_data points to this allocated memory. Further,

for ( n=0; n<a; n++ )
{
    printf ("Enter number #%d: ",n);
    scanf ("%d",&ptr_data[n]);
}

Writes beyond the bounds of the allocate memory:

ptr_data[n];

is equivalent to:

*(ptr_data + n);

Note that writing beyond the bounds of memory which belongs to you results in Undefined behavior in C and C++ both. With undefined behavior the program doesn't need to behave in any specific way.It many work correctly or crash or show any random behavior, simple the behavior is undefined.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • but its working. so you say that the compiler allocates the memory automatically? This is one beautiful explanation btw! Thanks! – bks4line Dec 04 '13 at 16:18
  • @bks4line: A [good read](http://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior).It is important to understand these concepts if you are working on C and C++. – Alok Save Dec 04 '13 at 16:21
0

The line ptr_data = (int*) malloc ( sizeof(int) ) allocates memory for only one integer pointer. You're trying to assign more than one value into ptr_data. If you want to do this, then:

ptr_data = malloc (sizeof(int) * a); 

This will give the pointer room for int a integers.

trifork
  • 57
  • 1
  • 10