Objekt einer struct, mit Array als Datenelement, via malloc initialsieren



  • Guten Abend,

    struct foo // sizeof(foo) == 1 Byte
    {
    	unsigned char byte[1];
    };
    
    int main()
    {
    	void* space = malloc(5);
    	foo f = *(foo*)space;
    
    	f.byte[0] = 0; // ok
    	f.byte[1] = 1; // ok?
    	f.byte[2] = 2; // ok?
    	f.byte[3] = 3; // ok?
    	f.byte[4] = 4; // ok?
    	f.byte[5] = 5; // an nun aber Speicherzugriffsverletzung.
    
    	return 0;
    }
    

    Ich allokiere 5 Bytes. Ein Objekt von foo benötigt man jedoch nur 1 Byte. Jetzt frage ich mich, ob ich auf die restlichen Bytes zugreifen darf, oder ob es eine Speicherzugriffsverletzung ist?

    Danke



  • void* space = malloc(5);
    	foo f = *(foo*)space;
    

    Da wird eine Kopie angelegt. f hat nichts mehr mit space zu tun.



  • struct foo // sizeof(foo) == 1 Byte
    {
    	unsigned char byte[1];
    };
    
    int main()
    {
    	void* space = malloc(5);
    	foo f = *(foo*)space; /* reserviert einen Speicherbereich von sizeof(f) Bytes, in den sizeof(struct foo) Bytes ab Adresse space kopiert werden */
    
    	f.byte[0] = 0; // ok
    	f.byte[1] = 1; // ok? /* ok, wenn sizeof(f)>1 */
    	f.byte[2] = 2; // ok? /* ok, wenn sizeof(f)>2 */
    	f.byte[3] = 3; // ok? /* ok, wenn sizeof(f)>3 */
    	f.byte[4] = 4; // ok? /* ok, wenn sizeof(f)>4 */
    	f.byte[5] = 5; // ok? /* ok, wenn sizeof(f)>5 */
    
    	return 0;
    }
    


  • ah, ok, danke euch beiden. 🙂

    struct foo // sizeof(foo) == 1 Byte
    {
        unsigned char byte[1];
    };
    
    int main()
    {
        void* space = malloc(5);
        foo* pf = (foo*)space;
    
        pf->byte[3] = 3; // ok
        pf->byte[4] = 4; // ok
        pf->byte[5] = 5; // nicht ok
    }
    

    Bei diesem Codebeispiel sind die ersten beiden Zugriffe definitiv gültig, erst der letztere Zugriff wäre ungültig, richtig?


Anmelden zum Antworten