Home > Mobile >  First element of Struct is lost when writing Struct to void pointer
First element of Struct is lost when writing Struct to void pointer

Time:06-14

I have a function that writes custom structs to some kind of "data block" (struct) that I created, which contains a void pointer that can store a custom struct. I created a function to write and to read to that specific void pointer but unfortunately, the first element of the returned struct always returns as "80" instead of it's original value. Here's the code:

#include <stdio.h>
#include <malloc.h>

typedef struct dataBlock {
    void* dataObject;
} DataBlock;

typedef struct testingStruct {

    int testingInt1;
    int testingInt2;

}TestObject;

void dataWriter(DataBlock *dataBlock, void* inputObject, int objSize) {
    if (objSize > 255) {
        printf("Error. Maximum 255 Bytes of data can be stored.");
        exit(0);
    }
    dataBlock->dataObject = malloc(objSize 1); // Allocates the size of dataObject plus one byte to store the size of the data Object.
    ((char*)dataBlock->dataObject)[0] = (char)objSize; //Stores the size of the data object to position 0 in the void*
    for (int i = 1; i < objSize;   i) {
        ((char*)dataBlock->dataObject)[i] = (char)((char*)inputObject)[i];
    }
}

void* dataGetter(DataBlock *dataBlock) {
    void* dataToReturn = malloc(((int)((char*)dataBlock->dataObject)[0])); // Creates Container to store read data using Void* Pos 0 in dataObject

    for (int i = 1; i < (int)(((char*)dataBlock->dataObject)[0]);   i) {
        ((char*)dataToReturn)[i] = (char)((char*)dataBlock->dataObject)[i]; //writes each byte of data to return to dataToReturn
    }
    return dataToReturn;
}

int main() {
    TestObject *testObject = malloc(sizeof(TestObject));
    testObject->testingInt1 = 74;

    testObject->testingInt2 = 49;

    DataBlock *dataBlockToStore = malloc(sizeof(DataBlock));

    dataWriter(dataBlockToStore, testObject, sizeof(TestObject));

    TestObject *testObjectCpy = dataGetter(dataBlockToStore); // Reads data from Block and generates another TestObject
    printf("%d\n", testObjectCpy->testingInt1); // Should be 74
    printf("%d\n", testObjectCpy->testingInt2); // Returned Correctly


    return 0;
}

I am unsure, if I am either reading or writing the data in the wrong way but the first variable in the written testingStruct always returns a wrong value.

CodePudding user response:

for (int i = 1; i < objSize;   i) {
    ((char*)dataBlock->dataObject)[i] = (char)((char*)inputObject)[i];

Array indices are zero-based. You are skipping the first element.

You need to do e.g. (avoid i and 'l' in loops when adding 1.....)

for (int j = 0; j < objSize;   j) {
    ((char*)dataBlock->dataObject)[j 1] = (char)((char*)inputObject)[j];

You could alternatively use memcpy.

You should also assert/fail if the size is above 255

Also, if you make dataBlock a char* you will need to perform less casting.

  • Related