c - 添加到字符串开头的额外字符?

标签 c

我有两个额外的字符被添加到我的字符串的开头,我似乎无法找出原因。这些字符甚至没有出现在代码中。我在这里不知所措。这是我的代码:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char *chars;

char* vector(char input, char *newlist);

int main(){

    char *input, *out = "Input: ";

    printf("Enter characters: ");                   
    while(1){
        char i = getchar();                         //get input
        if(i == '\n'){
            break;                                  //detect a return key
        } else{
            input = vector(i, input);               //call vector
        }
    }

    char * print = (char *)malloc(1 + strlen(input) + strlen(out));
    strcpy(print, out);                             //concat the strings
    strcat(print, input);

    printf("\n%s", print);                          //print array

    free(print);
    free(input);
    free(chars);

    return 0;                                       //exit
}

char* vector(char in, char *newlist){

    int length = strlen(newlist);                   //determine length of newlist(input)

    chars = (char*)calloc(length+2, sizeof(char));  //allocate more memory
    strcpy(chars, newlist);                         //copy the array to chars
    chars[length] = in;                             //appened new character
    chars[length + 1] = '\0';                       //append end character

    return chars;
}

出于某种原因,代码产生了这个:

Enter characters: gggg

Input: PEgggg

什么时候应该产生这个:

Enter characters: gggg

Input: gggg

最佳答案

@MikeCat 所说的所有要点都是正确的,只是要补充一点,calloc 分配的内存未被释放,这会导致内存泄漏。您可以像@M.M 在评论中所说的那样释放它,但是下次为了避免内存泄漏,您可以使用valgrind:

Let's take your program, as hash.c. Got to the command line and compile it, for eg :

gcc hash.c -Wall

If your program compiles successfully, an executable or out file will appear. As we have not specified the name of the executable, it's default name will be a.out. So let's run it with valgrind:

valgrind -- leak-check=full ./a.out

This will run executable, along with valgrind, and if there is a memory leak, it will show it when the executable ends.


If you do not have valgrind installed, you can install it from here.

关于c - 添加到字符串开头的额外字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35691841/

相关文章:

c++ - 控制投影仪的单个像素

检查子字符串是否存在以及存在的位置

字节顺序可以指字节中的位顺序吗?

c - 为什么我在函数结束时收到错误?

c - 在 PBC 库中导入和导出相同元素

c - 如何使用 SoX C 库混合音频文件

C、Windows API在注册表项后创建文件夹结构

c - 为什么一个字节的大小必须是8位?

c - 程序的数组迭代

c++ - 将 C++ 实例方法分配给全局函数指针?