Char *在malloc之后返回垃圾值?

时间:2016-04-28 01:11:33

标签: c char malloc

此函数理想情况下采用字符串并根据整数返回超过第一个单词(或"命令")的字母。即:

input: "write 1234"      //valLen = 4  and  inputStr = "write 1234"
output: "1234"          

"提取器功能":

char* ExtractValue(unsigned int *valLen, char *inputStr)
{
int sizeToAllocate = strlen(inputStr) - (strlen(inputStr) - *valLen) + 1;
unsigned int i = 0;
int count = 0;

/* memory aloc */
printf("Assigning %d bits of space...\n", sizeToAllocate);
char *outStr = (char*)malloc(sizeToAllocate);
if (!outStr)
{
    perror("Error allocating memory");
    abort();
}

/*sets final string to value entered*/
for (i = 0; i < strlen(inputStr); i++)
{
    if (strlen(inputStr) - i <= *valLen)
    {
        outStr[count] = inputStr[i];
        count++;
    }
}

return outStr;
}

它在很大程度上起作用;但是,由于某种原因,返回字符串始终由垃圾值继续。似乎malloc()outstr初始化为已使用的内存(其中包含一堆乱码),for循环将字符添加到其开头。一个例子是:

input: "write 1234"
output: "1234══²²²²¼"

为什么会这样做?非常感谢任何解释,谢谢!

1 个答案:

答案 0 :(得分:1)

你已经回答了自己的问题! malloc只是分配内存,并且不需要清除以前的内容。您可以使用calloc来获取已被清零的内存块,或修改您的循环以在字符串的末尾添加空字符。

/*sets final string to value entered*/
for (i = 0; i < strlen(inputStr); i++)
{
    if (strlen(inputStr) - i <= *valLen)
    {
        outStr[count] = inputStr[i];
        count++;
    }
}

/* null terminate the string */
outStr[count++] = "\0";