I started learning C, and I don't understand what I'm doing wrong. Here is a simple code of a function that returns the pid+".data".
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
char * getfilename(){
char name[60];
sprintf(name,"%i.data",getpid());
return name;
}
void main(){
char* name = getfilename();
printf("%s",name);
}
outputs: ��#�a
.
So I guess that I'm doing something wrong.
char * getfilename(){
char name[60];
sprintf(name,"%i.data",getpid());
return name;
}
You cannot access name
object after getfilename
has returned. The lifetime of the automatic object name
ends at the getfilename
last }
. Accessing it after the function returns is undefined behavior.
As a temporary fix you can specify name
as static
and it will work. But what you should do is to have the getfilename
function accepts a pointer argument where the filename will be written.
EDIT:
Why I don't suggest to use strdup
?
strdup
is not a Standard C function. strdup
lives in the POSIX world. For portability reasons whenever I can, I prefer to use Standard C functions.strdup
performs a hidden malloc
call and you have not to forget to perform a free
. This is contrary to all functions of the Standard C library which never call malloc
(or actually that never appear to call malloc
). strdup
is a bad API design.strdup
is performing a copy of a string. Why do you need to perform an extra copy? Just write the string in a place you can retrieve it.