使用malloc时遇到问题

Sha*_*ars 0 c malloc c-strings

在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'
Run Code Online (Sandbox Code Playgroud)

对于另一个变量,它的值是: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
}
Run Code Online (Sandbox Code Playgroud)

con*_*gus 5

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