【发布时间】:2010-12-11 23:24:20
【问题描述】:
我用char* memoryChunk = malloc ( 80* sizeof(char) + 1); 分配了一块内存,是什么阻止我写入超过81 个单位的内存位置?我能做些什么来防止这种情况发生?
void testStage2(void) {
char c_str1[20] = "hello";
char* ut_str1;
char* ut_str2;
printf("Starting stage 2 tests\n");
strcat(c_str1, " world");
printf("%s\n", c_str1); // nothing exciting, prints "hello world"
ut_str1 = utstrdup("hello ");
ut_str1 = utstrrealloc(ut_str1, 20);
utstrcat(ut_str1, c_str1);
printf("%s\n", ut_str1); // slightly more exciting, prints "hello hello world"
utstrcat(ut_str1, " world");
printf("%s\n", 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] != '\0'; j++){
if ((i+j-1) == 20)
return s;
s[i+j] = suffix[j];
}
//strcpy(s, suffix);
s[i + j] = '\0';
return s;
}// append the suffix to s
【问题讨论】:
-
sizeof(char)根据定义是1。如果要乘以大小,请改用sizeof *memoryChunk:malloc((80 + 1) * sizeof *memoryChunk);。例如,如果您稍后将 memoryChunk 更改为wchar_t *,您将不必编辑 malloc 参数。 -
第一个
strcat()非常危险。strcat()要求目标缓冲区有空间来追加新字符串;您的代码不能以任何方式保证这一点。 -
因为 c_str 被分配了 20 个位置,所以包含“hello world”就足够了
-
好电话 - 完全无法阅读。我看到了
c_str1[] = "hello";。 -
从问题中删除(C 编程)——这就是标签的用途。
标签: c memory-management malloc