This is the code I have so far:
char * duplicate(char *str)
{
int len = strlen(str) + 1;
char *ptr;
ptr = (char *)malloc(len);
strcpy(ptr, str);
str = (char *)realloc((void *)str, len * 2 * sizeof(char));
strcat(str, ptr);
free((void *)ptr);
present(str);
return(str);
}
sidenote: I know I should be checking if the memory is actually allocated, I will do so later.
The program asks the user to input a string, proceeds to double it and prints out the new string.
present->a
function I made so it would print the string out.
Now my thought process was as follows:
1) Allocate memory to a placeholder pointer, copy str
string onto ptr
2) Reallocate memory for str
, now with double the size
3) Using strcat
to copy the string
4) Freeing ptr
memory
Output should be as follows:
string input by users for example: "Hi"
output: "HiHi"
If we run the function again output should be: "HiHiHiHi"
The problem I am facing is, after running the function around 2-4 times (depends on the input string size) the program will crash, it will say it had a trigger point and something along the lines of: "wntdll.pdb not loaded".
I believe it has something to do with the memory, because if I am trying to duplicate larger strings, it will simply crash after the first time.
Am I allocating memory properly? I am not sure what to do at this point.
Thanks for the help :)