在使用malloc时出现问题

问题描述:

在GDB中执行此程序,并且在它通过目标/替换malloc语句后,[1]元素总是给出一个尴尬的值。在使用malloc时出现问题

例如(使用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' 

对于其他变量,它的值是:取代[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

您不需要在c程序中投射malloc的返回值。 – 2013-02-11 03:16:51

malloc只分配内存;它不会保证内容是什么。如果要用0初始化存储器内容,请尝试calloc

+0

好吧,非常感谢。 – juice 2013-02-11 03:37:27

malloc不清除内存,所以你得到垃圾在你分配的块。您可以使用calloc自动清除内存或memset手动清除它。