I make programs in C. I read about the strdup()
function. From what I could tell, the strdup()
function allocates space while the strcpy()
does not. But the problem with strdup()
is it allocates space but does not free it. strdupa()
allocates and frees space. But at some places I read that the strdupa()
function is dangerous. It would be helpful if someone could tell me why strdupa()
is dangerous. Also, when I tried to run a program in my Open Suse 12.1 32 bit system, gcc, gave an error which told that strdupa()
does not exist. If strdupa()
is a dangerous function, can someone tell me the duplicate of strdupa()
and the headers to use when using the function.
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
The
strdupa()
function is documented to use thealloca()
function to allocate memory. That means its memory is freed when the function returns. Thealloca()
function is not singularly portable; thestrdupa()
function is likewise not all that portable.The manual page documents that the
strdupa()
function is only available when you compile with-D_GNU_SOURCE
, or if you usegcc -std=gnu11
or something similar.If you need to access the memory after the function that calls
strdupa()
returns, then you cannot usestrdupa()
—strdup()
is necessary. If you're worried about portability, you probably usestrdup()
, though even that is only defined by POSIX (strdup()
) and not by Standard C. Note thatstrdup()
is part of TR 24731-2: Extensions to the C Library - Part II: Dynamic allocation functions. AFAIK,alloca()
is not part of either POSIX or the proposed extensions to the Standard C library.It depends on your definition of 'danger'. Yes. If there isn't enough space on the stack for the string, then
strdupa()
will fail whenstrdup()
won't. There are those who are not enamoured ofalloca()
and therefore they are not keen on code that usesalloca()
. Thealloca()
manual page has an extensive set of notes about the problems, one of which is that you can't tell whenalloca()
has failed.You look for core dumps; if the program crashes, it was perhaps because of an
alloca()
allocation failure. Usingvalgrind
might spot the problem; you still can't reliably recover from the problem, though, and you probably won't have your production code running undervalgrind
, so it is at most a diagnostic aid. If you want reliable behaviour, usestrdup()
— and accept that you need to manually free the allocated memory.From the manual page for
alloca()