C/Please explain the concept of dynamic memory allocation with an example
Expert: Zlatko - 4/7/2010
QuestionWhy the following program prints the string more than 6 characters although declared as 6 characters?
#include<stdlib.h>
main()
{
char *s;
s=(char *)malloc(6);
printf("\n Enter a string....");
gets(s);
puts(s);
}
Also if scanf is written its not working Displaying the error as segmentation fault. Why this happens? And if this is wrong Tell me the correct program Please.......
AnswerHello
The gets() has no way of knowing how much space is allocated for s. It will overwrite past the end of the allocated space. That corrupts memory and the results are unpredictable. In this case the program worked, but generally such a program will fail, often at some other point far away from the gets function call. You saw this when you added the scanf. It is better to use fgets. The fgets allows you to specify the available space in s.