memory dellocation

C

c.arnet

Hi there,

I've written a function that 'converts' a structure of type timeval to
a c-string:

char *tv2Str(struct timeval tvX)
{
char caStr[20];
char *cpResult;

sprintf(caStr, "%ld.%ld", tvX.tv_sec, tvX.tv_usec);

cpResult = (char *)malloc(sizeof(char)*strlen(caStr));
strcpy(cpResult, caStr);

return cpResult;
}

I use it like this:

printf("%s", tv2Str((struct timeval){123, 456}) );

Question:
How (if at all) does the compiler (gcc) ensure that the memory
allocated in the above function is deallocated after the printf call ?

Thanks,
Cornel
 
R

Richard Bos

char *tv2Str(struct timeval tvX)
{
char *cpResult;
cpResult = (char *)malloc(sizeof(char)*strlen(caStr));

There's no need to cast malloc(). It returns a void *, which can be
assigned to any kind of object pointer without a cast. You _did_
return cpResult;
}
I use it like this:

printf("%s", tv2Str((struct timeval){123, 456}) );
How (if at all) does the compiler (gcc) ensure that the memory
allocated in the above function is deallocated after the printf call ?

It doesn't, so this is a bad way to call that function.

Richard
 
J

j

There's no need to cast malloc(). It returns a void *, which can be
assigned to any kind of object pointer without a cast.

_any_? What about a pointer to a function?
 
N

Neil Cerutti

j said:
(e-mail address removed) (Richard Bos) wrote in message


_any_? What about a pointer to a function?

If it were possible to do, it would be useless.

#include <stdlib.h>
int main(void)
{
int (*pf)(void) = malloc(sizeof *pf); /* ??? */
*pf = main; /* ??? */
return EXIT_FAILURE;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top