-1

I just want to concatenate two strings and a separator using a function. But in main() I am not getting the concatenated string.

#include <stdio.h>
#include <string.h>
 #include <stdlib.h>

char* PathCreation(char* Str1, char* Str2, char* Separator=(char*)"/"){

    char CreatedPath[strlen(Str1)+strlen(Str2)+strlen(Separator)+1];
    strncpy(&CreatedPath[0], Str1, strlen(Str1));
    strncpy(&CreatedPath[strlen(Str1)], Separator, strlen(Separator));
    strncpy(&CreatedPath[strlen(Str1)+1], Str2, strlen(Str2));
    CreatedPath[strlen(Str1)+strlen(Str2)+1]='\0';
    //printf("\n%s", CreatedPath);
    return CreatedPath;

}
int main(void)
{

    char str1[] = "foo";
    char str2[] = "bar";

    char* ccat=PathCreation(str1, str2);


    puts(str1);
    puts(str2);
    puts(ccat);

}
  • 1
    You’re returning a pointer to an array that’s allocated on the stack. This results in Undefined Behaviour. You need to either allocate on the heap or allocate in the parent stack-frame. – Dai May 18 '19 at 14:39
  • 1
    Last time I checked, C did not support default argument values. – wildplasser May 18 '19 at 14:43
  • This "*`char* PathCreation(..., char* Separator=(char*)"/")`*" is not C. – alk May 18 '19 at 14:45
  • Aside of the fix others proposed already, instead of this complicated usage of the dangerous `strncpy()` just start with `strcpy()` followed by using `strcat()`s. – alk May 18 '19 at 14:53

1 Answers1

1

Since you've been programming in C style, I'll stick to C style. But I should point out that your code is only valid in C++ because of the default argument.

The issue is that when you simply declare something you're allocating it to the stack, stacks are destroyed once a function exits and attempting to use data after the stack has been destroyed is undefined behaviour, which means that the code may work as you expect on occasion but it may also end up pointing to garbage or simply crashing.

Instead you'll need to allocate it on the heap so that it persists after the function exits. Replace the line where you allocate your string with:

  char* CreatedPath = (char*)malloc(sizeof(char)*(strlen(Str1)+strlen(Str2)+strlen(Separator)+1));
0x777C
  • 993
  • 7
  • 21