Given an absolute path I am trying to get the part that comes after a certain directory. getTargetPath function does that and when I compile and run the code below, the code gives me the expected output.
The problem is when I remove the printf("\n") before the line with malloc in main, I get:
malloc(): corrupted top size
Aborted (core dumped)
So when I put a printf("\n") before or after the line with malloc the code seems to work fine but when I remove it, I get the error above.
My question is, why does this happen? I am not asking for a solution to my problem with the path string. I just want to learn what causes this behavior.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char* getTargetPath(const char* source)
{
int count = 0;
int i = 0;
while(*source)
{
if (*source == '/')
{
++count;
if (count == 4)
{
break;
}
}
++source;
}
return source;
}
int main()
{
const char* backup_path = "/home/ofy/real_2";
char temp1[] = "/home/dir1/dir2/dir3/dir4/dir5";
const char* s1 = temp1;
const char* s2 = getTargetPath(s1);
printf("\n");
char* full_path = (char*)malloc(strlen(backup_path) * sizeof(char));
strcpy(full_path, backup_path);
strcat(full_path, s2);
printf("%s\n", full_path);
return 0;
}