+ Reply to Thread
Results 1 to 2 of 2

Thread: What is alloca? Should we use it?

  1. #1

    What is alloca? Should we use it?

    Hi,

    What is alloca? Should we use it?

    Regards.

  2. #2
    Senior Member
    Join Date
    Feb 2012
    Posts
    109
    Hi,

    'alloca' allocates memory on stack and still returns a pointer to it.

    Code:
    struct CStudent
    {
    	int m_nRoleID ;
    	char m_szName[100] ;
    } ;
    
    void UseAlloca()
    {
    	//Humm, this is a pointer but does not leak memory. no need to free the memory!
    	void *pData = _alloca(sizeof(CStudent)) ;
    
    	CStudent *pStudent = (CStudent *) pData ;
    
    	pStudent->m_nRoleID = 10 ;
    	strncpy(pStudent->m_szName, "Mohit", sizeof(pStudent->m_szName)) ;
    
    	//Oops, this leaks memory
    	char *pChars = new char[100] ;
    
    	//uncomment the below lines to make sure memory does not leak.
    	//delete []pChars ;
    	//pChars = NULL ;
    }
    Note:
    a. It allocates memory on stack.
    b. User does not need to free the memory explicitly. Allocated space is automatically freed when function exits.
    c. For more information; http://msdn.microsoft.com/en-us/library/wb1s57t5.aspx

    Thanks

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts