unsigned int *a;
	a = (int*)malloc(1*sizeof(int));
	a[0] = 10;
	a[1] = 20;
	a[100] = 40;
	printf("%u",a[100]);

I have created a pointer named a and allocated 'single' int space for it but still i can store and retrieve more than that. This code runs. Then what is the need of malloc? What is the problem with this method? can i trust the data outside of boundary?

there is no problem with malloc() -- what you see is called undefined behavior, or array out-of-bounds error. The compiler won't complain about it because it assumes (usually wrongly) that you know what you are doing. What happens when you do that? The program just scribbles stuff all over memory, destroy whatever happens to be in memory at the time. Sometimes your program will crash, and sometimes not, depending what was in memory at the time.

The way to fix that problem -- Don't do that :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.