我似乎找不到与我正在做的事情完全匹配的问题,所以就这样吧。下面是我的 C 应用程序的精简版本,可以解决问题所在。我知道这是丑陋的代码并且缺少一些错误检查,但这只是让我找出这个问题。就目前而言,下面的示例应将所有“A”转换为“BCDE”。代码中的注释描述了这个问题。(首先执行runMe)
int runMe2(char *in, char **buffer) {
long x;
long b_size = 0;
long i_size = 1000;
long i = 0;
char t_buffer[1006];
// Initial malloc small as it will grow
*buffer = (char *)malloc(2*sizeof(char));
strcpy(*buffer, "");
for (x = 0; x < 999; x++)
t_buffer[x] = 0;
for (x = 0; x < strlen(in); x++) {
if (i >= i_size) {
char *r_buffer;
b_size = b_size + 1006*sizeof(char);
i_size = 0;
// Here is where the problem is.
// The first time through, i=1000, b_size=1006 and everything is fine
// The second time throgh, i=1004, b_size=2012 and the heap crashes on the realloc
r_buffer = (char *)realloc(*buffer, b_size);
if (r_buffer == NULL)
exit(0);
*buffer = r_buffer;
strcat(*buffer, t_buffer);
for (x = 0; x < 999; x++)
t_buffer[x] = 0;
}
if (in[x] == 'A') {
t_buffer[i++] = 'B';
t_buffer[i++] = 'C';
t_buffer[i++] = 'D';
t_buffer[i++] = 'E';
}
}
}
int runMe() {
char *out;
char in[30000];
int x = 0;
// Set up a 29,999 character string
for (x = 0; x < 30000; x++)
in[x] = 'A';
in[29999] = 0;
// Send it as pointer so we can do other things here
runMe2(in, &out);
// Eventually, other things will happen here
free(out);
}