我遇到其中realloc
调用似乎修改另一个字符串,keyfile
的内容的问题。的realloc()似乎影响已分配的内存
它应该通过的空终止char*
(密钥文件),它包含正上方500个字符来运行。但是,问题是我在while
-loop中执行的reallocation
似乎修改了密钥文件的内容。
我试图与realloc
除去动态再分配和代替大小为200*sizeof(int)
代替初始化在for
-loop指针。问题仍然存在,keyfile
字符串在内存(重新)分配期间被修改,我不知道为什么。我已经通过在malloc
和realloc
语句之前和之后打印keyfile-string来证实了这一点。
注:密钥文件只包含字符a-z
,没有数字,空格,换行或大写。只有26个文字,小写字母。
int **getCharMap(const char *keyfile) {
char *alphabet = "abcdefghijklmnopqrstuvwxyz";
int **charmap = malloc(26*sizeof(int));
for (int i = 0; i < 26; i++) {
charmap[(int) alphabet[i]] = malloc(sizeof(int));
charmap[(int) alphabet[i]][0] = 0; // place a counter at index 0
}
int letter;
int count = 0;
unsigned char c = keyfile[count];
while (c != '\0') {
int arr_count = charmap[c][0];
arr_count++;
charmap[c] = realloc(charmap[c], (arr_count+1)*sizeof(int));
charmap[c][0] = arr_count;
charmap[c][arr_count] = count;
c = keyfile[++count];
}
// Just inspecting the results for debugging
printf("\nCHARMAP\n");
for (int i = 0; i < 26; i++) {
letter = (int) alphabet[i];
printf("%c: ", (char) letter);
int count = charmap[letter][0];
printf("%d", charmap[letter][0]);
if (count > 0) {
for (int j = 1; j < count+1; j++) {
printf(",%d", charmap[letter][j]);
}
}
printf("\n");
}
exit(0);
return charmap;
}
的valgrind的valgrind的valgrind – bmargulies 2014-10-30 15:59:45
应该是'INT **字符表= malloc的(26 *的sizeof(INT *))'中如果您运行的是64位系统(或者极少数情况下是带有16位寄存器的32位系统)。 – 2014-10-30 16:01:00