views:

85

answers:

4

#include<stio.h>
main()
{
  int *p,i;
  p = (int*)malloc(sizeof(int));
  printf("Enter:");
  scanf("%d",p);
  for(i=1;i<3;i++)
  {
   printf("Enter");
   scanf("%d",p+i);
  }

  for(i=0;i<3;i++)
  {
    printf("No:%d\n",*(p+i));
  }
  getch();
  return 0;
}

In this C program memory is accessed without allocation.The program works.Will any problem arise by accessing memory without allocation?If yes then what is the solution for storing a collection of integer data which the size is not known in advance?

+4  A: 

Yes, it leads to undefined behavior. The problem is working here purely becuase of luck and may crash any time. The solution is to allocate the memory using malloc For example if you want to allocate memory for count number of elements then you can use int* p = (int*)malloc(sizeof(int)*count);. From here on you can access p as an array of count elements.

Naveen
And I'd say it is **bad luck** that it appears to work. Crash early, loudly, and often as my mentor used to say.
RBerteig
+1  A: 

Accessing unallocated memory leads to undefined behavior. Exactly what happens will depends on a variety of conditions. It may "work" now but you could see problems when you extend your program.

If you don't know how many items you want to read, there are a couple of strategies to use.

  1. Use realloc to grow the buffer as you need more space.
  2. Use a linked list instead of an array
R Samuel Klatchko
+2  A: 

It likely works because the memory immediately after *p is both accessible (allocated in the VM system and has the right bits set), and not in use for anything else. This could all change if malloc finds you some bytes immediately before an inaccessible page; or if you move to a malloc implementation that uses the trailing space for bookkeeping.

So it's not really safe.

Edmund
A: 

Most definitely yes. Its just pure luck that you can access without allocating. malloc does not what memory you are using and that could result in serious problems.

Hence its a compulsion (i don't want to use the word better here) to allocate memory according to your needs and then use it.

Some problems which could result are:

  1. Segmentation fault
  2. Memory corruption

and it may result in giving you headache for hours when the behavior is undefined. For eg: the location of a crash may not be the exact place of origin of the problem.

Praveen S