lcc tmpnam崩溃

时间:2013-04-07 09:05:44

标签: c

当我使用lcc编译器并调用tmpnam(buf)时,程序崩溃了。

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.  

我怎么了,怎么解释这个行为。

1 个答案:

答案 0 :(得分:0)

man tmpnam逐字逐句

  

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


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

tmpnam()生成的名称包含最大L_tmpnam长度前缀的文件名,其名称为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);