openFile(argv[1],"r");
while(characterBuff != EOF)
{
characterBuff = fgetc(examFile);
memoryAlloc += 1;
string = expandRealloc(string, memoryAlloc);
appendString(string, characterBuff);
printf("%s\n", string);
}
closeFile();
free(string);
在下面的代码:我是从得到的printf的输出给了我喜欢[somehash] d [somehash] E [somehash] S [somehash]ķ打印文件的内容
ackward值我得到的输出字是“DESK”,但是从内存中取出所有类型的随机垃圾,我做错了什么?
注意:以下内容已分配给malloc(sizeof(char)),并在每次将单个字符添加到字符串时进行实时定位。
即输出我应该得到应为: d 德 德 台的 而是说我得到我之前所示的U的事情。
编辑:
char* expandRealloc(char* ptrS, size_t n)
{
void *tmp;
if((tmp = realloc(ptrS, n)) == NULL)
{
printf("Error: Memory leak possible; Closing Program");
exit(EXIT_FAILURE);
}
else
{
ptrS = tmp;
return ptrS;
}
}
我写了一个包装功能的realloc。感谢您的帮助,但它仍然不能解决问题,当尝试打印结果时,我仍然得到[somecrapmemoryhash] [letter] [somecrapmemoryhash] [letter]。
置字符串:
void appendString(char* inputString, int inputChar)
{
int stringLenght = strlen(inputString);
inputString[stringLenght - 1] = inputChar;
inputString[stringLenght] = '\0';
}
我想这是C/C++? –
是的,它是C,忘了添加 –
开始的一个大问题 - 你的realloc调用中断 - 查看realloc的手册页 –