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.
You cannot access
nameobject aftergetfilenamehas returned. The lifetime of the automatic objectnameends at thegetfilenamelast}. Accessing it after the function returns is undefined behavior.As a temporary fix you can specify
nameasstaticand it will work. But what you should do is to have thegetfilenamefunction accepts a pointer argument where the filename will be written.EDIT:
Why I don’t suggest to use
strdup?strdupis not a Standard C function.strduplives in the POSIX world. For portability reasons whenever I can, I prefer to use Standard C functions.strdupperforms a hiddenmalloccall and you have not to forget to perform afree. This is contrary to all functions of the Standard C library which never callmalloc(or actually that never appear to callmalloc).strdupis a bad API design.strdupis 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.