Std :: malloc () und das Leben des Objekts beginnenC++

Programme in C++. Entwicklerforum
Anonymous
 Std :: malloc () und das Leben des Objekts beginnen

Post by Anonymous »

Auszug aus dem Buch "C ++ Memory Management" von Patrice Roy < /p>

Die std :: memcpy () Funktion < /h4>
Für historische (und c -Kompatibilität). Eine
falsche Verwendung von std :: memcpy () für den Typ Punning wäre wie folgt: < /p>

Code: Select all

// suppose this holds for this example
static_assert(sizeof(int) == sizeof(float));
#include 
#include 
#include 
int main() {
   float f = 1.5f;
    void *p = malloc(sizeof f);
    assert(p);
    int *q = std::memcpy(p, &f, sizeof f);
    int value = *q; // UB
    //
}
< /code>
Der Grund, warum dies illegal ist, besteht darin, dass der Aufruf an std :: memcpy ()
ein Float -Objekt in den Speicher kopiert, auf das P durch P, effektiv
die Lebensdauer eines Float -Objekts in diesem Speicher startet. Da q ein
int*ist, ist dasferencing es ub. Nicht malloc () 
erstellt implizit einen int (wenn sizeof (int) == sizeof (float) natürlich) und wir können legal memcpy dazu durchführen und es als Wert lesen.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post