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?
In the below code
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
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 bymalloc()
, causing memory leak. You don't need to usemalloc()
here, just assign the literal to the pointer and use that as the second argument in thestrcat()
call.