0

newbie to C language here. I am not sure of the difference between allocating memory to a file through malloc, and doing

typedef uint8_t BYTE;
    BYTE filename[//number of bytes]

For instance reading the start of a file and checking for jpeg, we are using the latter to check for the first 4 bytes for its "signature". This involves "fread" function in order to read the first 4 bytes and temporarily store it in this place called filename. Won't I be doing the same thing with malloc? Not sure what is the exact difference between the 2.

Thanks everyone in advance for answering my question!

3
  • 2
    You need a good book on C. malloc is a dynamic memory allocation function. Only in the he farthest stretches of imagination is it related to file io, and there generally only when managing the memory you're transferring data to/from the file stream. There are other ways to provide memory when doing said-same io, including using automatic storage space or global/static storage space. The exceptionally brief tow lines you show is using one of those.
    – WhozCraig
    Mar 3, 2022 at 9:11
  • 1
    This question, in correct form, should be "the difference b/w memory status of malloc & memory status of predefined array of the form []." When BYTE fname[5] is used, consecutive 5 memory spaces, each 8 bytes long, will be allocated as soon as the executable is loaded into memory. When BYTE *fname = malloc(5 * sizeof(uint8_t)) is used, related 5 memory spaces will be allocated at run time, i.e. when the corresponding malloc statement is reached.
    – ssd
    Mar 3, 2022 at 9:20
  • typedef uint8_t BYTE; is horrible practice. You should use the idiomatic standardized type uint8_t and not invent some secret, local type standard.
    – Lundin
    Mar 3, 2022 at 9:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.