简体   繁体   English

c malloc防止缓冲区溢出

[英]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? 使用上面的代码,我把NULL放入64字节? (to prevent buffer overflow) (防止缓冲区溢出)

Even if your code was correct (see @Dietrich's answer), it doesn't prevent buffer overflow. 即使你的代码是正确的(参见@Dietrich的答案),它也不会阻止缓冲区溢出。 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");

A pointer can be seen as an array, in C. However, your code is wrong. 指针可以看作C中的数组。但是,您的代码是错误的。

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. 当您运行memset(host, 0x00, host[63]) ,它将存储在host[63]的值作为memset的长度传递。 This is an error, since host is uninitialized, host[63] is garbage and you should not pass garbage to memset . 这是一个错误,因为host未初始化, host[63]是垃圾,你不应该将垃圾传递到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. \\0字节放入host的最后一个插槽并不能避免大多数缓冲区溢出。 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. 术语说明:我更喜欢使用NULL来引用C中名为“NULL”的无效指针,而NUL引用ASCII字符串中的零字节。 Eg, 例如,

// 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM