I wonder why the following code does not throw segmentation fault when a string literal which is a result of dirname() is modified but throws segmentation fault when a string literal created in a usual is modified:
#include <stdio.h>
#include <stdlib.h>
#include <libgen.h>
#define FILE_PATH "/usr/bin/screen"
int main(void)
{
char db_file[] = FILE_PATH;
char *filename = dirname(db_file);
/* no segfault here */
filename[1] = 'a';
/* segfault here */
char *p = "abc";
p[1] = 'z';
exit(0);
}
I know that it's an UB to modify a string literal so output I get may be perfectly valid but I wonder if this can be explained. Are string literals that are returned by functions treated differently by compilers? The same situation happens when I compile this code with Clang 3.0 on x86 and gcc on x86 and ARM.