Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can gets() exceed memory allocated by malloc()?

Tags:

c

I have a doubt in malloc and realloc function, When I am using the malloc function for allocating the memory for the character pointer 10 Bytes. But when I am assigning the value for that character pointer, it takes more than 10 bytes if I try to assign. How it is possible.

For example:

main()
{
    char *ptr;
    ptr=malloc(10*sizeof(char));
    gets("%s",ptr);
    printf("The String is :%s",ptr);
}

Sample Output:

$./a.out
hello world this is for testing

The String is :hello world this is for testing

Now look at the output the number of characters are more than 10 bytes. How this is possible, I need clear explanation. Thanks in Advance.

like image 572
Q_SaD Avatar asked Jul 13 '26 05:07

Q_SaD


2 Answers

That's why using gets is an evil thing. Use fgets instead.

malloc has nothing to do with it.

Don't use gets().

Admittedly, rationale would be useful, yes? For one thing, gets() doesn't allow you to specify the length of the buffer to store the string in. This would allow people to keep entering data past the end of your buffer, and believe me, this would be Bad News.

Detailed explanation:

First, let's look at the prototype for this function:

#include <stdio.h>
char *gets(char *s);

You can see that the one and only parameter is a char pointer. So then, if we make an array like this:

char buf[100];

we could pass it to gets() like so:

gets(buf)

So far, so good. Or so it seems... but really our problem has already begun. gets() has only received the name of the array (a pointer), it does not know how big the array is, and it is impossible to determine this from the pointer alone. When the user enters their text, gets() will read all available data into the array, this will be fine if the user is sensible and enters less than 99 bytes. However, if they enter more than 99, gets() will not stop writing at the end of the array. Instead, it continues writing past the end and into memory it doesn't own.

  1. This problem may manifest itself in a number of ways:

  2. No visible affect what-so-ever

  3. Immediate program termination (a crash)

  4. Termination at a later point in the programs life time (maybe 1 second later, maybe 15 days later)

  5. Termination of another, unrelated program

  6. Incorrect program behavior and/or calculation ... and the list goes on. This is the problem with "buffer overflow" bugs, you just can't tell when and how they'll bite you.

like image 134
haccks Avatar answered Jul 15 '26 20:07

haccks


You just got an undefined behavior. (More information here)

Use fgets and not gets !

like image 21
Joze Avatar answered Jul 15 '26 18:07

Joze