Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic allocation in C

I'm writing a program and I have the following problem:

char *tmp;
sprintf (tmp,"%ld",(long)time_stamp_for_file_name);

Could someone explain how much memory allocate for the string tmp.

How many chars are a long variable?

Thank you,

I would appreciate also a link to an exahustive resource on this kind of information.

Thank you

UPDATE:

Using your examples I got the following problem:

root@-[/tmp]$cat test.c

       #include <stdio.h>
       int
       main()
       {
            int len;
            long time=12345678;
            char *tmp;
            len=snprintf(NULL,0,"%ld",time);
            printf ("Lunghezza:di %ld %d\n",time,len);      
            return 0;
       }

root@-[/tmp]$gcc test.c
root@-[/tmp]$./a.out 
Lunghezza:di 12345678 -1
root@-[/tmp]$

So the len result from snprintf is -1, I compiled on Solaris 9 with the standard compiler.

Please help me!

like image 643
Kerby82 Avatar asked Nov 29 '22 05:11

Kerby82


1 Answers

If your compiler conforms to C99, you should be able to do:

char *tmp;
int req_bytes = snprintf(NULL, 0, "%ld",(long)time_stamp_for_file_name);
tmp = malloc(req_bytes +1); //add +1 for NULL
if(!tmp) {
    die_horrible_death();
}
if(snprintf(tmp, req_bytes+1, "%ld",(long)time_stamp_for_file_name) != req_bytes) {
    die_horrible_death();
}

Relevant parts of the standard (from the draft document):

  • 7.19.6.5.2: If n is zero, nothing is written, and s may be a null pointer.
  • 7.19.6.5.3: The snprintf function returns the number of characters that would have been written had n been sufficiently large, not counting the terminating null character, or a negative value if an encoding error occurred. Thus, the null-terminated output has been completely written if and only if the returned value is nonnegative and less than n.

If this is not working, I'm guessing your compiler/libc does not support this part of c99, or you might need to explicitly enable it. Wh I run your example (with gcc version 4.5.0 20100610 (prerelease), Linux 2.6.34-ARCH), I get

$./example
Lunghezza:di 12345678 8

like image 107
gnud Avatar answered Dec 15 '22 03:12

gnud