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;
}
You're not allocating enough space for full_path
:
char* full_path = (char*)malloc(strlen(backup_path) * sizeof(char));
It needs to be at least as long as backup_path
and s2
, plus 1 for the terminating null byte, but you only have enough for backup_path
. This results in you writing past the end of allocated memory which invokes undefined behavior.
With undefined behavior, you can't predict what your program will do. It could crash, it could output strange results, or it can appear to work properly. Also, making a seemingly unrelated code change can change how UB manifests itself. This is exactly what you saw when you removed the printf
call. With the printf
the program "worked" while without it the program crashed.
To allocate the proper amount of space:
char* full_path = (char*)malloc(strlen(backup_path) + strlen(s2) + 1);
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