Search code examples
cpointersdynamic-memory-allocationstring-literalsstrcat

Why is the result of strcat empty


char* path = malloc(128);
path = "/bin/"
char* path2 = malloc(128);
path2 = "ls"
strcat(path,path2);
fprintf(stderr, "%s\n",path);

The result is empty.

But if I use

char path[128] = "/bin/";
char* path2 = malloc(128);
path2 = "ls"
strcat(path,path2);
fprintf(stderr, "%s\n",path);

what is the difference between char path[128] and malloc?


Solution

  • In the below code

    char* path = malloc(128);
    path = "/bin/";                   //added ;, you're overwriting the returned pointer
    char* path2 = malloc(128);
    path2 = "ls";                     // same as above
    strcat(path,path2);               // the destination buffer is non-modifiable!!
    fprintf(stderr, "%s\n",path);
    

    you're essentially overwriting the memory (pointer) returned by allocator function, and making those pointers point to string literal. The strcat() call, thus, invokes undefined behaviour, as the destination buffer is non-modifiable (as they're string literal). This invokes undefined behaviour.

    The second snippet is less problematic

    char path[128] = "/bin/";   // this is to be used as destination, OK
    char* path2 = malloc(128);
    path2 = "ls";               // you wouldn't need malloc here            
    strcat(path,path2);
    fprintf(stderr, "%s\n",path);
    

    here, you're allocating a large enough array (which is modifiable and can be used as a legit destination buffer for strcat()), so from that aspect you're okay. However, for the second argument, you're again overwriting the pointer returned by malloc(), causing memory leak. You don't need to use malloc() here, just assign the literal to the pointer and use that as the second argument in the strcat() call.