Sunteți pe pagina 1din 20

new Operator

The new operator attempts to dynamically allocate (at run time) one or more objects of type-name. The new operator cannot be used to allocate a function; however, it can be used to allocate a pointer to a function. Syntax allocation-expression : ::opt new placementopt new-type-name new-initializeropt ::opt new placementopt ( type-name ) new-initializeropt placement : ( expression-list ) new-type-name : type-specifier-list new-declaratoropt The new operator is used to allocate objects and arrays of objects. The new operator allocates from a program memory area called the free store. !n ", the free store is often referred to as the heap. #hen new is used to allocate a single object, it yields a pointer to that object; the resultant type is new-type-name * or type-name *. #hen new is used to allocate a singly dimensioned array of objects, it yields a pointer to the first element of the array, and the resultant type is new-type-name * or type-name *. #hen new is used to allocate a multidimensional array of objects, it yields a pointer to the first element of the array, and the resultant type preserves the si$e of all but the leftmost array dimension. %or e&ample:
new float[10][25][10]

yields type float (*)[25][10]. Therefore, the following code will not wor' because it attempts to assign a pointer to an array of float with the dimensions [25][10] to a pointer to type float:
float *fp; fp = new float[10][25][10];

The correct e&pression is:


float (*cp)[25][10]; cp = new float[10][25][10];

The definition of cp allocates a pointer to an array of type float with dimensions [25] [10] ( it does not allocate an array of pointers. )ll but the leftmost array dimensions must be constant e&pressions that evaluate to positive values; the leftmost array dimension can be any e&pression that evaluates to a positive value. #hen allocating an array using the new operator, the first dimension can be $ero ( the new operator returns a uni*ue pointer. The type-specifier-list cannot contain const, volatile, class declarations, or enumeration declarations. Therefore, the following e&pression is illegal:
volatile char *vch = new volatile char[20];

The new operator does not allocate reference types because they are not objects. !f there is insufficient memory for the allocation re*uest, by default operator new returns NULL. +ou can change this default behavior by writing a custom e&ception,handling routine and calling the _set_new_handler run,time library function with your function name as its argument. %or more details on this recovery scheme, see The operator new %unction.

How new Works


The allocation-expression ( the e&pression containing the new operator ( does three things:

-ocates and reserves storage for the object or objects to be allocated. #hen this stage is complete, the correct amount of storage is allocated, but it is not yet an object. !nitiali$es the object(s). .nce initiali$ation is complete, enough information is present for the allocated storage to be an object. /eturns a pointer to the object(s) of a pointer type derived from new-type-name or type-name. The program uses this pointer to access the newly allocated object.

The new operator invo'es the function operator new. %or arrays of any type, and for objects that are not of class, str ct, or nion types, a global function, ::operator new, is called to allocate storage. "lass,type objects can define their own operator new static member function on a per,class basis. #hen the compiler encounters the new operator to allocate an object of type type, it issues a call to type::operator new( si!eo"( type ) ) or, if no user,defined operator new is defined, ::operator new( si!eo"( type ) ). Therefore, the new operator can allocate the correct amount of memory for the object.

Note The argument to operator new is of type si!e_t. This type is defined in 0!/1"T.2, 3)--.".2, 313./+.2, 41)/"2.2, 4T001%.2, 4T0!..2, 4T0-!5.2, 4T/!67.2, and T!31.2. )n option in the synta& allows specification of placement (see 4ynta& for new .perator). The placement parameters can be used only for user,defined implementations of operator new; it allows e&tra information to be passed to operator new. )n e&pression with a placement field such as
T *TObject = new ( 0x00 0 ) T;

is translated to
T *TObject = T!!operator new( "i#eof( T )$ 0x00 0 );

The original intention of the placement field was to allow hardware,dependent objects to be allocated at user,specified addresses. Note )lthough the preceding e&ample shows only one argument in the placement field, there is no restriction on how many e&tra arguments can be passed to operator new this way. 1ven when operator new has been defined for a class type, the global operator can be used by using the form of this e&ample:
T *TObject =!!new TObject;

The scope,resolution operator (::) forces use of the global new

#he operator new $ nction


#hen a statement such as the following is encountered in a program, it translates into a call to the function operator new:
char *pch = new char[%&''()*+,-(];

!f the re*uest is for $ero bytes of storage, operator new returns a pointer to a distinct object (that is, repeated calls to operator new return different pointers). !f there is insufficient memory for the allocation re*uest, by default operator new returns NULL. +ou can change this default behavior by writing a custom e&ception,handling routine and calling the _set_new_handler run,time library function with your function name as its argument. %or more details on the recovery scheme, see the following section, 2andling !nsufficient 3emory "onditions. The two scopes for operator new functions are described in Table 88.9.

#a%le &&'( Scope "or operator new $ nctions Operator ::operator new Scope 7lobal

class-name::operator new "lass

The first argument to operator new must be of type si!e_t (a type defined in 4T001%.2), and the return type is always void *. The global operator new function is called when the new operator is used to allocate objects of built,in types, objects of class type that do not contain user,defined operator new functions, and arrays of any type. #hen the new operator is used to allocate objects of a class type where an operator new is defined, that class:s operator new is called. )n operator new function defined for a class is a static member function (which cannot, therefore, be virtual) that hides the global operator new function for objects of that class type. "onsider the case where new is used to allocate and set memory to a given value:
.incl/0e 12alloc3h4 .incl/0e 12e2or53h4 cla"" %lan6" 7 p/blic! %lan6"()78 voi0 *operator new( "i#e*t "t9llocate%loc6$ char ch,nit ); 8; voi0 *%lan6"!!operator new( "i#e*t "t9llocate%loc6$ char ch,nit ) 7 voi0 *pvTe2p = 2alloc( "t9llocate%loc6 ); if( pvTe2p := 0 ) 2e2"et( pvTe2p$ ch,nit$ "t9llocate%loc6 ); ret/rn pvTe2p; 8

%or discrete objects of type %lan6", the global operator new function is hidden. Therefore, the following code allocates an object of type %lan6" and initiali$es it to 0xa5:
int 2ain() 7 %lan6" *a5 = new( 0xa5 ) %lan6"; 8 ret/rn a5 := 0;

The argument supplied in parentheses to new is passed to %lan6"!!operator new as the ch,nit argument. 2owever, the global operator new function is hidden, causing code such as the following to generate an error:
%lan6" *+o2e%lan6" = new %lan6";

%or previous versions of the compiler, nonclass types and all arrays (regardless of whether they were of class type) allocated using the new operator always used the global operator new function. 5eginning with ;isual "<< =.>, the compiler supports member array new and delete operators in a class declaration. %or e&ample:
cla"" ; 7 p/blic! voi0* voi0 8;

operator new[] ("i#e*t); operator 0elete[] (voi0*);

voi0 f() 7 ; *p; = new ;[5]; 0elete [] p;; 8

#he operator delete $ nction


3emory that is dynamically allocated using the new operator can be freed using the delete operator. The delete operator calls the operator delete function, which frees memory bac' to the available pool. ?sing the delete operator also causes the class destructor (if there is one) to be called. There are global and class,scoped operator delete functions. .nly one operator delete function can be defined for a given class; if defined, it hides the global operator delete function. The global operator delete function is always called for arrays of any type. The global operator delete function, if declared, ta'es a single argument of type void *, which contains a pointer to the object to deallocate. The return type is void (operator delete cannot return a value). Two forms e&ist for class,member operator delete functions:
voi0 operator 0elete( voi0 * ); voi0 operator 0elete( voi0 *$ "i#e*t );

.nly one of the preceding two variants can be present for a given class. The first form wor's as described for global operator delete. The second form ta'es two arguments, the first of which is a pointer to the memory bloc' to deallocate and the second of which is the number of bytes to deallocate. The second form is particularly useful when an operator delete function from a base class is used to delete an object of a derived class.

The operator delete function is static; therefore, it cannot be virtual. The operator delete function obeys access control, as described in "hapter 8>, 3ember,)ccess "ontrol. The following e&ample shows user,defined operator new and operator delete functions designed to log allocations and deallocations of memory:
.incl/0e 1io"trea23h4 .incl/0e 1"t0lib3h4 int f<o=>e2or5 = 0; ?? @erfor2 lo==in= (0=no; non#ero=5e")A int c%loc6"9llocate0 = 0; ?? Bo/nt of bloc6" allocate03 ?? &"erC0efine0 operator new3 voi0 *operator new( "i#e*t "t9llocate%loc6 ) 7 "tatic f,nOpDew = 0; ?? E/ar0 fla=3 if( f<o=>e2or5 FF :f,nOpDew ) 7 f,nOpDew = 1; clo= 11 G>e2or5 bloc6 G 11 HHc%loc6"9llocate0 11 G allocate0 for G 11 "t9llocate%loc6 11 G b5te"InG; f,nOpDew = 0; 8 ret/rn 2alloc( "t9llocate%loc6 ); 8 ?? &"erC0efine0 operator 0elete3 voi0 operator 0elete( voi0 *pv>e2 ) 7 "tatic f,nOpJelete = 0; ?? E/ar0 fla=3 if( f<o=>e2or5 FF :f,nOpJelete ) 7 f,nOpJelete = 1; clo= 11 G>e2or5 bloc6 G 11 CCc%loc6"9llocate0 11 G 0eallocate0InG; f,nOpJelete = 0; 8 free( pv>e2 ); 8 int 2ain( int ar=c$ char *ar=v[] ) 7 f<o=>e2or5 = 1; ?? T/rn lo==in= on3 if( ar=c 4 1 ) for( int i = 0; i 1 atoi( ar=v[1] ); HHi ) 7 char *p>e2 = new char[10]; 0elete[] p>e2; 8 8 ret/rn c%loc6"9llocate0;

The preceding code can be used to detect memory lea'age ( that is, memory that is allocated on the free store but never freed. To perform this detection, the global new and delete operators are redefined to count allocation and deallocation of memory. 5eginning with ;isual "<< =.>, the compiler supports member array new and delete operators in a class declaration. %or e&ample:
cla"" ; 7 p/blic! voi0* voi0 8;

operator new[] ("i#e*t); operator 0elete[] (voi0*);

voi0 f() 7 ; *p; = new ;[5]; 0elete [] p;; 8

delete Operator
The delete operator deallocates an object created with the new operator. The delete operator has a result of type void and therefore does not return a value. The operand to delete must be a pointer returned by the new operator. ?sing delete on a pointer to an object not allocated with new gives unpredictable results. +ou can, however, use delete on a pointer with the value >. This provision means that, because new always returns > on failure, deleting the result of a failed new operation is harmless. Syntax deallocation-expression : ::opt delete cast-expression ::opt delete @ A cast-expression ?sing the delete operator on an object deallocates its memory. ) program that dereferences a pointer after the object is deleted can have unpredictable results or crash. !f the operand to the delete operator is a modifiable l,value, its value is undefined after the object is deleted. Bointers to const objects cannot be deallocated with the delete operator.

Usin) delete

There are two syntactic variants for the delete operator: one for single objects and the other for arrays of objects. The following code fragment shows how these differ:
voi0 2ain() 7 ?? 9llocate a /"erC0efine0 object$ &JObject$ an0 an object ?? of t5pe 0o/ble on the free "tore /"in= the ?? new operator3 &JT5pe *&JObject = new &JT5pe; 0o/ble *0Object = new 0o/ble; 333 ?? Jelete the two object"3 0elete &JObject; 0elete 0Object; 333 ?? 9llocate an arra5 of /"erC0efine0 object" on the ?? free "tore /"in= the new operator3 &JT5pe (*&J9rr)[K] = new &JT5pe[5][K]; 333 ?? &"e the arra5 "5ntax to 0elete the arra5 of object"3 0elete [] &J9rr; 8

These two cases produce undefined results: using the array form of delete (delete @ A) on an object and using the nonarray form of delete on an array.

*e+ory ,llocation
?se these routines to allocate, free, and reallocate memory. *e+ory-,llocation .o tines .o tine Calloca calloc CcallocCdbg Ce&pand Ce&pandCdbg free Use )llocate memory from stac' )llocate storage for array, initiali$ing every byte in allocated bloc' to > 0ebug version of calloc; only available in the debug versions of the run,time libraries 1&pand or shrin' bloc' of memory without moving it 0ebug version of _expand; only available in the debug versions of the run,time libraries %ree allocated bloc'

CfreeCdbg CgetCsbhCthreshold Cheapadd Cheapch' Cheapmin Cheapset Cheapwal' malloc CmallocCdbg Cmsi$e Cmsi$eCdbg C*ueryCnewChandler C*ueryCnewCmode realloc CreallocCdbg CsetCnewChandler

0ebug version of "ree; only available in the debug versions of the run,time libraries /eturn the upper limit for the si$e of a memory allocation that will be supported by the small,bloc' heap )dd memory to heap "hec' heap for consistency /elease unused memory in heap %ill free heap entries with specified value /eturn information about each entry in heap )llocate bloc' of memory from heap 0ebug version of +alloc; only available in the debug versions of the run,time libraries /eturn si$e of allocated bloc' 0ebug version of _+si!e; only available in the debug versions of the run,time libraries /eturn address of current new handler routine as set by _set_new_handler /eturn integer indicating new handler mode set by _set_new_+ode for +alloc /eallocate bloc' to new si$e 0ebug version of realloc; only available in the debug versions of the run,time libraries 1nable error,handling mechanism when new operator fails (to allocate memory) and enable compilation of 4tandard Template -ibraries (4T-) 4et new handler mode for +alloc 4et the upper limit for the si$e of a memory allocation that will be supported by the small,bloc' heap

CsetCnewCmode CsetCsbhCthreshold

Send feedback to MSDN. Look here for MSDN Online resources.

+alloc
)llocates memory bloc's. void *+alloc( si!e_t size )/ .o tine +alloc .e0 ired Header Dstdlib.hE and Dmalloc.hE 1o+pati%ility )64!, #in F=, #in 6T

%or additional compatibility information, see "ompatibility in the !ntroduction. Li%raries -!5".-!5 -!5"3T.-!5 4ingle thread static library, retail version 3ultithread static library, retail version

34;"/T.-!5 !mport library for 34;"/T.0--, retail version

.et rn 2al e +alloc returns a void pointer to the allocated space, or NULL if there is insufficient memory available. To return a pointer to a type other than void, use a type cast on the return value. The storage space pointed to by the return value is guaranteed to be suitably aligned for storage of any type of object. !f si$e is >, +alloc allocates a $ero,length item in the heap and returns a valid pointer to that item. )lways chec' the return from +alloc, even if the amount of memory re*uested is small. 3ara+eter size 5ytes to allocate .e+arks The +alloc function allocates a memory bloc' of at least size bytes. The bloc' may be larger than size bytes because of space re*uired for alignment and maintenance information.

The startup code uses +alloc to allocate storage for the _environ, envp, and ar)v variables. The following functions and their wide,character counterparts also call +alloc: calloc fscanf Cgetw Cpopen printf putc putchar Cputenv puts Cputw scanf Csearchenv setvbuf Cspawn functions Cstrdup system Ctempnam ungetc vfprintf vprintf

Ce&ec functions fsee' fgetc Cfgetchar fgets fprintf fputc Cfputchar fputs fread fsetpos Cfullpath fwrite getc getchar Cgetcwd Cgetdcwd gets

The "<< CsetCnewCmode function sets the new handler mode for +alloc. The new handler mode indicates whether, on failure, +alloc is to call the new handler routine as set by CsetCnewChandler. 5y default, +alloc does not call the new handler routine on failure to allocate memory. +ou can override this default behavior so that, when +alloc fails to allocate memory, +alloc calls the new handler routine in the same way that the new operator does when it fails for the same reason. To override the default, call
*"et*new*2o0e(1)

early in your program, or lin' with 61#3.01..5G. #hen the application is lin'ed with a debug version of the " run,time libraries, +alloc resolves to CmallocCdbg. %or more information about how the heap is managed during the debugging process, see ?sing " /un,Time -ibrary 0ebugging 4upport. 4xa+ple
?* >9<<OB3B! Thi" pro=ra2 allocate" 2e2or5 with * 2alloc$ then free" the 2e2or5 with free3 *? .incl/0e 1"t0lib3h4 .incl/0e 1"t0io3h4 .incl/0e 12alloc3h4 ?* 'or *>9;*@9TL 0efinition *?

voi0 2ain( voi0 ) 7 char *"trin=; ?* 9llocate "pace for a path na2e *? "trin= = 2alloc( *>9;*@9TL ); if( "trin= == D&<< ) printf( G,n"/fficient 2e2or5 availableInG ); el"e 7 printf( G>e2or5 "pace allocate0 for path na2eInG ); free( "trin= ); printf( G>e2or5 free0InG ); 8 8

O tp t
>e2or5 "pace allocate0 for path na2e >e2or5 free0

3emory )llocation /outines See ,lso calloc, free, realloc

realloc
/eallocate memory bloc's. void *realloc( void *memblock5 si!e_t size )/ .o tine realloc .e0 ired Header Dstdlib.hE and Dmalloc.hE 1o+pati%ility )64!, #in F=, #in 6T

%or additional compatibility information, see "ompatibility in the !ntroduction. Li%raries -!5".-!5 -!5"3T.-!5 4ingle thread static library, retail version 3ultithread static library, retail version

34;"/T.-!5 !mport library for 34;"/T.0--, retail version

.et rn 2al e realloc returns a void pointer to the reallocated (and possibly moved) memory bloc'. The return value is NULL if the si$e is $ero and the buffer argument is not NULL, or if there is not enough available memory to e&pand the bloc' to the given si$e. !n the first case, the original bloc' is freed. !n the second, the original bloc' is unchanged. The return value points to a storage space that is guaranteed to be suitably aligned for storage of any type of object. To get a pointer to a type other than void, use a type cast on the return value. 3ara+eters memblock Bointer to previously allocated memory bloc' size 6ew si$e in bytes .e+arks The realloc function changes the si$e of an allocated memory bloc'. The memblock argument points to the beginning of the memory bloc'. !f memblock is NULL, realloc behaves the same way as +alloc and allocates a new bloc' of size bytes. !f memblock is not NULL, it should be a pointer returned by a previous call to calloc, +alloc, or realloc. The size argument gives the new si$e of the bloc', in bytes. The contents of the bloc' are unchanged up to the shorter of the new and old si$es, although the new bloc' can be in a different location. 5ecause the new bloc' can be in a new memory location, the pointer returned by realloc is not guaranteed to be the pointer passed through the memblock argument. realloc calls +alloc in order to use the "<< CsetCnewCmode function to set the new handler mode. The new handler mode indicates whether, on failure, +alloc is to call the new handler routine as set by CsetCnewChandler. 5y default, +alloc does not call the new handler routine on failure to allocate memory. +ou can override this default behavior so that, when realloc fails to allocate memory, +alloc calls the new handler routine in the same way that the new operator does when it fails for the same reason. To override the default, call
*"et*new*2o0e(1)

early in your program, or lin' with 61#3.01..5G. #hen the application is lin'ed with a debug version of the " run,time libraries, realloc resolves to CreallocCdbg. %or more information about how the heap is managed during the debugging process, see ?sing " /un,Time -ibrary 0ebugging 4upport. 4xa+ple
?* )(9<<OB3B! Thi" pro=ra2 allocate" a bloc6 of 2e2or5 for * b/ffer an0 then /"e" *2"i#e to 0i"pla5 the "i#e of that * bloc63 Dext$ it /"e" realloc to expan0 the a2o/nt of * 2e2or5 /"e0 b5 b/ffer an0 then call" *2"i#e a=ain to * 0i"pla5 the new a2o/nt of 2e2or5 allocate0 to b/ffer3 *? .incl/0e 1"t0io3h4 .incl/0e 12alloc3h4 .incl/0e 1"t0lib3h4 voi0 2ain( voi0 ) 7 lon= *b/ffer; "i#e*t "i#e; if( (b/ffer = (lon= *)2alloc( 1000 * "i#eof( lon= ) )) == D&<< ) exit( 1 ); "i#e = *2"i#e( b/ffer ); printf( G+i#e of bloc6 after 2alloc of 1000 lon="! M/InG$ "i#e ); ?* )eallocate an0 "how new "i#e! *? if( (b/ffer = realloc( b/ffer$ "i#e H (1000 * "i#eof( lon= )) )) == D&<< ) exit( 1 ); "i#e = *2"i#e( b/ffer ); printf( G+i#e of bloc6 after realloc of 1000 2ore lon="! M/InG$ "i#e ); free( b/ffer ); exit( 0 ); 8

O tp t
+i#e of bloc6 after 2alloc of 1000 lon="! 000 +i#e of bloc6 after realloc of 1000 2ore lon="! N000

3emory )llocation /outines See ,lso calloc, free, malloc

calloc
)llocates an array in memory with elements initiali$ed to >. void *calloc( si!e_t num5 si!e_t size )/ .o tine calloc .e0 ired Header 1o+pati%ility

Dstdlib.hE and Dmalloc.hE )64!, #in F=, #in 6T

%or additional compatibility information, see "ompatibility in the !ntroduction. Li%raries -!5".-!5 -!5"3T.-!5 4ingle thread static library, retail version 3ultithread static library, retail version

34;"/T.-!5 !mport library for 34;"/T.0--, retail version

.et rn 2al e calloc returns a pointer to the allocated space. The storage space pointed to by the return value is guaranteed to be suitably aligned for storage of any type of object. To get a pointer to a type other than void, use a type cast on the return value. 3ara+eters num 6umber of elements size -ength in bytes of each element .e+arks The calloc function allocates storage space for an array of num elements, each of length size bytes. 1ach element is initiali$ed to >.

calloc calls +alloc in order to use the "<< CsetCnewCmode function to set the new handler mode. The new handler mode indicates whether, on failure, +alloc is to call the new handler routine as set by CsetCnewChandler. 5y default, +alloc does not call the new handler routine on failure to allocate memory. +ou can override this default behavior so that, when calloc fails to allocate memory, +alloc calls the new handler routine in the same way that the new operator does when it fails for the same reason. To override the default, call
*"et*new*2o0e(1)

early in your program, or lin' with 61#3.01..5G. #hen the application is lin'ed with a debug version of the " run,time libraries, calloc resolves to CcallocCdbg. %or more information about how the heap is managed during the debugging process, see ?sing " /un,Time -ibrary 0ebugging 4upport. 4xa+ple
?* B9<<OB3B! Thi" pro=ra2 /"e" calloc to allocate "pace for * 0 lon= inte=er"3 ,t initiali#e" each ele2ent to #ero3 *? .incl/0e 1"t0io3h4 .incl/0e 12alloc3h4 voi0 2ain( voi0 ) 7 lon= *b/ffer; b/ffer = (lon= *)calloc( 0$ "i#eof( lon= ) ); if( b/ffer := D&<< ) printf( G9llocate0 0 lon= inte=er"InG ); el"e printf( GBanOt allocate 2e2or5InG ); free( b/ffer );

O/tp/t 9llocate0

0 lon= inte=er"

3emory )llocation /outines See ,lso free, malloc, realloc

"ree
0eallocates or frees a memory bloc'. void "ree( void *memblock )/

$ nction "ree

.e0 ired Header Dstdlib.hE and Dmalloc.hE

1o+pati%ility )64!, #in F=, #in 6T

%or additional compatibility information, see "ompatibility in the !ntroduction. Li%raries -!5".-!5 -!5"3T.-!5 4ingle thread static library, retail version 3ultithread static library, retail version

34;"/T.-!5 !mport library for 34;"/T.0--, retail version

.et rn 2al e 6one 3ara+eter memblock Breviously allocated memory bloc' to be freed .e+arks The "ree function deallocates a memory bloc' (memblock) that was previously allocated by a call to calloc, +alloc, or realloc. The number of freed bytes is e*uivalent to the number of bytes re*uested when the bloc' was allocated (or reallocated, in the case of realloc). !f memblock is NULL, the pointer is ignored and "ree immediately returns. )ttempting to free an invalid pointer (a pointer to a memory bloc' that was not allocated by calloc, +alloc, or realloc) may affect subse*uent allocation re*uests and cause errors. )fter a memory bloc' has been freed, Cheapmin minimi$es the amount of free memory on the heap by coalescing the unused regions and releasing them bac' to the operating system. %reed memory that is not released to the operating system is restored to the free pool and is available for allocation again. #hen the application is lin'ed with a debug version of the " run,time libraries, "ree resolves to CfreeCdbg. %or more information about how the heap is managed during the debugging process, see ?sing " /un,Time -ibrary 0ebugging 4upport.

4xa+ple
?* >9<<OB3B! Thi" pro=ra2 allocate" 2e2or5 with * 2alloc$ then free" the 2e2or5 with free3 *? .incl/0e 1"t0lib3h4 .incl/0e 1"t0io3h4 .incl/0e 12alloc3h4 voi0 2ain( voi0 ) 7 char *"trin=; ?* 9llocate "pace for a path na2e *? "trin= = 2alloc( *>9;*@9TL ); if( "trin= == D&<< ) printf( G,n"/fficient 2e2or5 availableInG ); el"e 7 printf( G>e2or5 "pace allocate0 for path na2eInG ); free( "trin= ); printf( G>e2or5 free0InG ); 8 8 ?* 'or *>9;*@9TL 0efinition *?

O tp t
>e2or5 "pace allocate0 for path na2e >e2or5 free0

3emory )llocation /outines

alloca
)llocates memory on the stac'. void *_alloca( si!e_t size )/ .o tine _alloca .e0 ired Header 1o+pati%ility Dmalloc.hE #in F=, #in 6T

%or additional compatibility information, see "ompatibility in the !ntroduction. Li%raries

-!5".-!5 -!5"3T.-!5

4ingle thread static library, retail version 3ultithread static library, retail version

34;"/T.-!5 !mport library for 34;"/T.0--, retail version

.et rn 2al e The _alloca routine returns a void pointer to the allocated space, which is guaranteed to be suitably aligned for storage of any type of object. To get a pointer to a type other than char, use a type cast on the return value. ) stac' overflow e&ception is generated if the space cannot be allocated. 3ara+eter size 5ytes to be allocated from stac' .e+arks _alloca allocates size bytes from the program stac'. The allocated space is automatically freed when the calling function e&its. Therefore, do not pass the pointer value returned by _alloca as an argument to free. There are restrictions to e&plicitly calling Calloca in an e&ception handler (12). 12 routines that run on &HI,class processors operate in their own memory frame : They perform their tas's in memory space that is not based on the current location of the stac' pointer of the enclosing function. The most common implementations include #indows 6T structured e&ception handling (412) and "<< catch clause e&pressions. Therefore, e&plicitly calling Calloca in any of the following scenarios results in program failure during the return to the calling 12 routine:

#indows 6T 412 e&ception filter e&pression: CCexcept ( alloca() ) #indows 6T 412 final e&ception handler: CC"inally J alloca() K "<< 12 catch clause e&pression

2owever, Calloca can be called directly from within an 12 routine or from an application,supplied callbac' that gets invo'ed by one of the 12 scenarios listed above. 3emory )llocation /outines See ,lso calloc, malloc, realloc

S-ar putea să vă placă și