I have two extra characters being added to the beginning of my string and I can't seem to find out why. The characters don't even appear in the code. I'm at a loss here. This is my code:
#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;
}
For some reason, the code produces this:
Enter characters: gggg
Input: PEgggg
When it should be producing this:
Enter characters: gggg
Input: gggg