0

When I use the lcc compiler and call tmpnam(buf) then the program crashes.

Reason: L_tmpnam indicates that buf must be 14 bytes long, while the string returned 
is "D:\Documents and settings\Paul\Temporary\TmP9.tmp" which is much longer than 14.  

What do I wrong, how can this behavior be explained.

4

1 回答 1

0

逐字逐句man tmpnam

切勿使用此功能。请改用 mkstemp(3) 或 tmpfile(3)。


无论如何,正如你所要求的:

生成的tmpnam()名称由最大L_tmpnam长度的文件名组成,前缀为 name 的目录P_tmpdir

tmpnam()因此,最好声明传递给的缓冲区(如果是 C99):

char pathname[strlen(P_tmpdir) + 1 + L_tmpnam + 1] = ""; /* +1 for dir delimiting `/` and +1 for zero-termination */

如果不是 C99,你可能会这样做:

size_t sizeTmpName = strlen(P_tmpdir) + 1 + L_tmpnam + 1;
char * pathname = calloc(sizeTmpName, sizeof (*pathname));
if (NULL == pathname)
  perror("calloc() for 'pathname'");

然后tmpnam()像这样调用:

if (NULL == tmpnam(pathname))
  fprintf(stderr, "tmpnam(): a unique name cannot be generated.\n");
else
  printf("unique name: %s\n", pathname);

... /* do soemthing */

/* if on non C99 and calloc(() was called: */
free(pathname);
于 2013-04-07T09:33:00.727 回答