Reputation: 11
This is the code I made.
If you erase the free function, it works well, but if you use the free function, the previous value remains.
I printed out the dest value for the test.
#include <stdlib.h>
#include <unistd.h>
void ft_strcpy(char *dest, char *str)
{
while (*dest)
{
dest++;
}
while (*str)
{
*dest = *str;
dest++;
str++;
}
}
int get_str_len(char *str)
{
int len;
len = 0;
while (*str)
{
len++;
str++;
}
return (len);
}
#include <stdio.h>
char *ft_strjoin(int size, char **strs, char *sep)
{
char *dest;
int len;
int i;
if (size > 0)
len = get_str_len(sep) * (size - 1);
i = 0;
while(i < size)
{
len += get_str_len(strs[i]);
i++;
}
dest = (char *)malloc(sizeof(char) * len);
printf("%s", dest);
len = get_str_len(dest);
if (dest == NULL)
{
dest = (char *)malloc(sizeof(char));
*dest = '\0';
return (dest);
}
i = 0;
while(i < size)
{
ft_strcpy(dest, strs[i]);
if (i != size - 1)
ft_strcpy(dest, sep);
i++;
}
return (dest);
}
This is main
The main function is for testing and there is nothing wrong with the part where I call up the code I wrote.
int main(void)
{
int index;
char **strs;
char *separator;
char *result;
strs = (char**)malloc(4 * sizeof(strs));
strs[0] = "lol";
strs[1] = "1234";
strs[2] = "poiuic";
strs[3] = "1234";
separator = " ";
index = 0;
printf("=====REAL ANSWER=====\n");
printf("result with size = 0 : $$\n");
printf("result with size = 1 : $lol$\n");
printf("result with size = 2 : $lol1234$\n");
printf("result with size = 3 : $lol1234poiuic$\n");
printf("=====YOUR ANSWER=====\n");
index = 0;
while (index < 4)
{
result = ft_strjoin(index, strs, separator);
printf("result with size = %d : $%s$\n", index, result);
index++;
free(result);
}
}
This is Result
=====REAL ANSWER=====
result with size = 0 : $$
result with size = 1 : $lol$
result with size = 2 : $lol1234$
result with size = 3 : $lol1234poiuic$
=====YOUR ANSWER=====
result with size = 0 : $$
result with size = 1 : $lol$
lolresult with size = 2 : $lollol 1234$
lollol 1234result with size = 3 : $lollol 1234lol 1234 poiuic$
Upvotes: 0
Views: 58
Reputation: 10038
The free()
function does not change the value stored in your pointer variable, nor does it necessarily release the previously-allocated memory from valid use by your program.
It does, however, remove from you any guarantee that you have any right to it. Hence, using it after calling free
is undefined behavior. (But will generally just get you an access violation and crash.)
Upvotes: 2