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
Method 2(Hash Map):- Create an empty hash table and insert all character of second string. Now remove all characters of first string. Remaining character is the extra character. Auxiliary Space:- O(n).
In python, to append a string in python we will use the ” + ” operator and it will append the variable to the existing string.
A simple solution to append a character to the end of a string is using the string concatenation operator (+) .
All the points @MikeCat are said are correct, just to add that the memory allocated by calloc
is not freed which leads to a memory leak. You can free
it as said by @M.M in a comment, but for next time, to avoid memory leaks, you can use 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With