本文介绍了从malloc()覆盖分配的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我一直在搞乱缓冲区,并且

我发现下面的代码将会运行没有分段错误的特殊情况。


据我所知,从调用malloc()中覆盖分配的空间

导致未定义

行为。


任何想法为什么要覆盖动态

分配的空间不会导致分段

错误?


#include< stdio.h>

#include< stdlib.h>

#include< string.h>

#include< errno.h>


int

main(无效)

{


char * ptr = NULL;

char buffer [256]; / *故意没有初始化* /

int y = 0;


if((ptr = malloc(1))== 0){

perror(" malloc()问题");

退出(1);

}


for(int i; i< 255; i ++)

buffer [i] =''Z'';


while((ptr [y ] = buffer [y])!=''\ 0'')

y ++;

(void)printf(" ptr is:%s \ n" ;,ptr);

免费(ptr);


返回0;

}


I have been messing around with buffers, and
I found it peculiar that the code below will
run without a segmentation fault.

As far as I know, overwriting the allocated space
from a call to malloc() results in undefined
behavior.

Any ideas why overwriting the dynamically
assigned space doesn''t cause a segmentation
fault?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int
main(void)
{

char *ptr = NULL;
char buffer[256]; /* intentionally did not initialize */
int y = 0;

if ( ( ptr = malloc(1) ) == 0 ) {
perror("malloc() problem");
exit(1);
}

for ( int i; i < 255; i++ )
buffer[i] = ''Z'';

while ( (ptr[y] = buffer[y]) != ''\0'' )
y++;
(void)printf("ptr is: %s\n", ptr);
free(ptr);

return 0;
}

推荐答案




因为定义的未定义行为可以是什么都没有。你好b / b
幸运,仅此而已。


-

Eric Amick

哥伦比亚,MD



Because undefined behavior by definition can be anything at all. You
were lucky, nothing more.

--
Eric Amick
Columbia, MD





为什么你会期望未定义的行为(UB)导致seg错误?

对我而言,UB似乎暗示任何事情都可能发生;好,坏,预期


或意外。



Why would you expect undefined behavior(UB) to cause seg fault?
To me, UB seems to suggest that anything can happen; good, bad, expected

or unexpected.





<<删除电子邮件的del>>



<<Remove the del for email>>


这篇关于从malloc()覆盖分配的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:10
查看更多