You are here:

C/Please explain the concept of dynamic memory allocation with an example

Advertisement


Question
Why 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.......

Answer
Hello

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.

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.