aligned_malloc

C/C++ este un limbaj multi-paradigmă de nivel mediu, orientat pe obiecte, folosit pe scară largă în industria software datorită echilibrului dintre viteză şi complexitate. Dacă ai nelămuriri în legătură cu acest limbaj sau vrei să ne înveți ceva chiar tu, intră aici.

aligned_malloc

Postby Adrian » 13 Jun 2010, 16:34

M-am lovit recent de nevoia de a aloca memorie aliniata la 16 octeti (standard pentru instructiuni SSE). Cum am gasit multe variante, implementari si solutii pe Internet (pe *nix exista functii, pe Windows existau), am incercat sa creez o varianta independenta de platforma care sa poata fi reutilizata usor. Apelurile la cele doua functii aligned_alloc si aligned_free pot fi inlocuite usor cu malloc/free cu aceeasi functionalitate. Eu am testat codul sub Windows/Visual C++ 2008, a functionat OK, postez aici si astept sugestii / imbunatatiri... dupa ce ne asiguram ca merge intr-adevar bine pe mai multe sisteme/compilatoare il putem adauga si la snippets:

  1.  
  2.  
  3. void* aligned_alloc(unsigned int number_of_bytes, unsigned int alignment)
  4. {
  5. #ifdef _MSC_VER
  6.     //we do not use aligned_malloc since MSDN documentation says it is incompatible with post-XP Windows
  7.     unsigned int displacement;
  8.     char *tempbuffer = (char *)malloc (number_of_bytes + sizeof(int) + alignment - 1);
  9.     assert(tempbuffer != NULL);
  10.  
  11.     //tempbuffer is displaced by sizeof(int) since we'll always store the total displacement just before the beginning of the buffer, regardless of address
  12.     tempbuffer += sizeof(int) + alignment - 1;
  13.     displacement = (unsigned int)tempbuffer % alignment;
  14.     //calculate final buffer start address
  15.     tempbuffer -= displacement;
  16.  
  17.     //store the total displacement size just before the allocated buffer
  18.     *( (unsigned int *) (tempbuffer - sizeof(int)) ) = sizeof(int) + alignment - 1 - displacement;
  19.     return tempbuffer;
  20.    
  21. #else
  22.     //*Nix systems _usually_ have memalign; use that on such platforms
  23.     return memalign(alignment, number_of_bytes);
  24. #endif
  25. }
  26.  
  27. void aligned_free(void *buffer)
  28. {
  29. #ifdef _MSC_VER
  30.     //if buffer was created using aligned_alloc, the sizeof(int) bytes before it hold a displacement value disp
  31.     //disp represents the number of positions skipped from the address returned by malloc in aligned_alloc
  32.     char *aux = (char *)buffer;
  33.     unsigned int disp;
  34.     disp = *( (unsigned int *) (aux - sizeof(int)) );
  35.     aux -= disp;
  36.     free(aux);
  37.     buffer = NULL;
  38. #else
  39.     free(buffer);
  40. #endif
  41. }
  42.  
  43.  
0,0p / 0 votes
User avatar
Adrian
Byte
 
Joined: 04 May 2010
Status: 13.5

Return to C / C++

Who is online

Users browsing this forum: No registered users and 0 guests