在GDB中运行此程序,在通过target / replace malloc语句后,[1]元素总是被赋予一个尴尬的值。
例如(使用GDB):
(gdb) p target[0]
$1 = -48 '\320'
(gdb) p target[1]
$2 = 101 'e'
(gdb) p target[2]
$3 = -4 '\374'
(gdb) p target[3]
$4 = -73 '\267'
对于另一个变量,它的值是:replace [1] ='d'
为什么这样做?如果我遗漏了任何其他重要信息,请告诉我。
void replace(char** list, int wordLine, int targetAmount)
{
char** final;
char* target;
char* replace;
int wCounter, cCounter, i, hashCounter = 0, addLetter = 0;
int copyWord, countChars, numOfWords, finalWords = 0;
target = (char*)malloc(targetAmount); //allocating memory for
replace = (char*)malloc(targetAmount); //these char*'s
// other stuff here
}
答案 0 :(得分:5)
malloc
仅分配内存;它不保证内容是什么。如果要使用0初始化内存内容,请尝试calloc
。
答案 1 :(得分:2)
malloc
不会清除内存,因此您在已分配的块中会出现垃圾。您可以使用calloc
自动清除内存,或memset
手动清除内存。