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/

相关文章:

java - 执行返回键而不是就地排序的搜索的技术

c++ - 我可以调用 memcpy() 和 memmove() 并将 "number of bytes"设置为零吗?

javascript - javascript如何分配内存?

C 标准库的综合开源测试套件

c - 灵活阵列成员的真正好处是什么?

c - 在头文件中声明结构

C++ 循环和 scanf 验证字母表、大写字母表和数字

c++ - 为什么按下的键的 dwControlKeyState 与常量不匹配?

c - 获取已连接 WiFi 网络的信号电平

c - 在这种情况下 && 和 & 有什么不同?