2013-04-07 81 views
0

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

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. 

我该怎么做,这种行为如何解释。

+3

请显示一些代码... – 2013-04-07 09:07:50

回答

0

逐字从man tmpnam

不要使用此功能。改为使用mkstemp(3)或tmpfile(3)。


无论如何,你问它:

通过tmpnam()所产生的名字由最大L_tmpnam lenght 的文件名前缀的与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); 
+0

所以buf需要长度L_tmpdir + L_tmpnam。感谢您的回答,我会尝试。 – 2013-04-07 09:36:27

+0

@PaulVerbelen:不要忘记为“字符串”零终止添加一个**字符! (看我的例子) – alk 2013-04-07 09:38:12

+0

@PaulVerbelen:我错了前缀。请看我更正的答案。 – alk 2013-04-07 09:44:06