如果我尝试访问 malloc() 区域之外的内存会发生什么? [英] What happens if I try to access memory beyond a malloc()'d region?
本文介绍了如果我尝试访问 malloc() 区域之外的内存会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经用 char* memoryChunk = malloc ( 80* sizeof(char) + 1);
分配了一块内存;是什么阻止我写入超过 81 个单位的内存位置?我能做些什么来防止这种情况发生?
I've allocated a chuck of memory with char* memoryChunk = malloc ( 80* sizeof(char) + 1);
What is keeping me from writing into the memory location beyond 81 units? What can I do to prevent that?
void testStage2(void) {
char c_str1[20] = "hello";
char* ut_str1;
char* ut_str2;
printf("Starting stage 2 tests
");
strcat(c_str1, " world");
printf("%s
", c_str1); // nothing exciting, prints "hello world"
ut_str1 = utstrdup("hello ");
ut_str1 = utstrrealloc(ut_str1, 20);
utstrcat(ut_str1, c_str1);
printf("%s
", ut_str1); // slightly more exciting, prints "hello hello world"
utstrcat(ut_str1, " world");
printf("%s
", ut_str1); // exciting, should print "hello hello world wo", 'cause there's not enough room for the second world
}
char* utstrcat(char* s, char* suffix){
int i = strlen(s),j;
int capacity = *(s - sizeof(unsigned) - sizeof(int));
for ( j =0; suffix[j] != ' '; j++){
if ((i+j-1) == 20)
return s;
s[i+j] = suffix[j];
}
//strcpy(s, suffix);
s[i + j] = ' ';
return s;
}// append the suffix to s
推荐答案
是什么让我无法写入超过 81 个单位的内存位置?
What is keeping me from writing into the memory location beyond 81 units?
没什么.但是,这样做会导致未定义的行为.这意味着任何事情都可能发生,你不应该依赖它两次做同样的事情.99.999% 的情况下这是一个错误.
Nothing. However, doing this results in undefined behaviour. This means anything can happen, and you shouldn't depend on it doing the same thing twice. 99.999% of the time this is a bug.
我能做些什么来防止这种情况发生?
What can I do to prevent that?
在访问(读取或写入)它们之前,始终检查您的指针是否在边界内.传递给字符串函数时,始终确保字符串以