我使用了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
参数。 - pmgstrcat()
很危险。strcat()
要求目标缓冲区有足够的空间来追加新字符串;你的代码没有任何保证。 - Carl Norumc_str1[] = "hello";
。 - Carl Norum