c - Extra characters added to beginning of string? -


i have 2 characters being added beginning of string , can't seem find out why. characters don't appear in code. i'm @ loss here. 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 = getchar();                         //get input         if(i == '\n'){             break;                                  //detect return key         } else{             input = vector(i, input);               //call vector         }     }      char * print = (char *)malloc(1 + strlen(input) + strlen(out));     strcpy(print, out);                             //concat 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 array chars     chars[length] = in;                             //appened new character     chars[length + 1] = '\0';                       //append end character      return chars; } 

for reason, code produces this:

enter characters: gggg  input: pegggg 

when should producing this:

enter characters: gggg  input: gggg 

you passed uninitialized input vector() , used it, invoked undefined behavior.

try changing char *input char *input = "".

also remove free(chars);, or encounter double-free problem.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -