polslinux
polslinux

Reputation: 1779

c malloc prevent buffer overflow

char *host;

host = malloc(64 * sizeof(char)); /* spazio per 64 caratteri */
memset(host,0x00,host[63]);

I have a doubt: pointer can be seen as an "array"??
With the above code am i putting NULL into the 64 byte? (to prevent buffer overflow)

Upvotes: 1

Views: 2417

Answers (2)

Dietrich Epp
Dietrich Epp

Reputation: 213278

A pointer can be seen as an array, in C. However, your code is wrong.

Correct version:

char *host;
host = malloc(64);   // sizeof(char) == 1, guaranteed by the standard
if (!host) abort();  // malloc can return NULL if it fails
host[63] = '\0';     // put NUL byte into the last element of array

When you run memset(host, 0x00, host[63]), it passes the value stored in host[63] as the length to memset. This is an error, since host is uninitialized, host[63] is garbage and you should not pass garbage to memset. If you are very lucky, your program will crash immediately. If you are unlucky, it will not.

Putting the \0 byte into the last slot of host does not avoid most buffer overflows. Most different types of buffer overflows need to be handled on an individual basis so there is no "one way" to prevent them.

Buffer overflows are a class of programming mistakes, and like most classes of mistakes, there are a lot of ways to make them. Each different buffer overflow is just a piece of incorrect code that needs to be fixed.

Terminology note: I prefer using NULL to refer to the invalid pointer named "NULL" in C, and NUL to refer to the zero byte in an ASCII string. E.g.,

// Initialize ptr to a NULL ptr...
char *ptr;
ptr = NULL;
ptr = 0; // equivalent to above

ptr = xmalloc(15);
// Set *ptr to the NUL byte...
*ptr = '\0';
*ptr = 0; // equivalent to above

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

Even if your code was correct (see @Dietrich's answer), it doesn't prevent buffer overflow. I can do this:

strcpy(host, "A very large string that's definitely a lot longer than 64 characters, so it will cause you a great deal of misery");

Upvotes: 2

Related Questions