I think I know the answer to my own question but I would like to have confirmation that I understand this perfectly.
I wrote a function that returns a string. I pass a char*
as a parameter, and the function modifies the pointer.
It works fine and here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void get_file_name(char* file_name_out)
{
char file_name[12+1];
char dir_name[50+12+1];
strcpy(file_name, "name.xml");
strcpy(dir_name, "/home/user/foo/bar/");
strcat(dir_name, file_name);
strcpy(file_name_out, dir_name); // Clarity - equivalent to a return
}
int main()
{
char file_name[100];
get_file_name(file_name);
printf(file_name);
return 0;
}
But if I replace char file_name[100];
by char *filename;
or char *filename = "";
, I get a segmentation fault in strcpy()
.
I am not sure why ?
My function takes a char*
as a parameter and so does strcpy()
.
As far as I understand, char *filename = "";
creates a read-only string. strcpy()
is then trying to write into a read-only variable, which is not allowed so the error makes sense.
But what happens when I write char *filename;
? My guess is that enough space to fit a pointer to a char
is allocated on the stack, so I could write only one single character where my file_name_out
points. A call to strcpy()
would try to write at least 2, hence the error.
It would explain why the following code compiles and yields the expected output:
void foo(char* a, char* b)
{
*a = *b;
}
int main()
{
char a = 'A', b = 'B';
printf("a = %c, b = %c\n", a, b);
foo(&a, &b);
printf("a = %c, b = %c\n", a, b);
return 0;
}
On the other hand, if I use char file_name[100];
, I allocate enough room on the stack for 100 characters, so strcpy()
can happily write into file_name_out
.
Am I right ?