If you like to concatenate strings in C you have to use strcat
.
If you like to copy one string to another you have to use strcpy
...
In a few words for string assignments in C you have to use a built in function (strcpy, strcat, memcpy, snprintf etc). You can't just simply use the =
operator as you do!
So your code would be something like this:
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <stdlib.h>
int main()
{
char input[255];
char *str1 = (char*)malloc(sizeof(char)*10);
strcpy(str1,"caingb");
char *str2=(char)0; //point to null..for initilization!
FILE *f;
f = fopen("rockyou.txt", "rt");
while (fgets(input, sizeof(input), f))
{
str2=(char*)malloc(sizeof(char)*(strlen(str1)+strlen(input))+1);
strcpy(str2,str1);
strcat(str2,input);
printf("%s", str2);
free(str2);
}
fclose(f);
free(str1);
return(0);
}
At the 2 lines of the code above that malloc function appears, you are basically allocating space on the memory, to store the variables that malloc gets called from. In your for the second malloc you need the size of each character (sizeof(char)
) multiplied times the amount of the length of string 1 (strlen(str1)
) plus the length of string 2 ('strlen(input)). That will give you the required memory in HEAP of your program to store
str2. For the first malloc i am just multiplying it by 10, since
"caingb"` i 6 chars (so i am reserving a few more bytes...not a good strategy if you want to be a good coder ;-) ). Later by calling free you are de-allocating the space you reserved with malloc, because if you don't it will stick like that into memory even after program is done executing!
A more abstract idea of malloc (for example purposes) would be
char* string=malloc(15);
...and like that you allocated 15 bytes of memory for the pointer char *string
. So in whatever this pointer points to, must not exceeds 15 bytes, or you will have memory leaks (aka segmantation faults in C).
For further reading, search yourself about stack and heap of a program in C.
Also always try out the man pages through the terminal of yours ( in Linux) . An example of this would be:
man malloc
..and voilla you will get a manual page for what malloc does. It might seems a little bit harsh to read those man pages at first, but give time to yourself! There is also an online version of them at http://man.he.net/
P.S. I haven't run the above code, but thats the general idea.