我有两个额外的字符被添加到我的字符串的开头,我似乎无法找出原因。这些字符甚至没有出现在代码中。我在这里不知所措。这是我的代码:
#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 bea.out
. So let's run it withvalgrind
: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/