1
char line[4096];
char filebuf;

I'm currently working on a STM32746G and I've managed to read a BMP file from a SD-card. The bytes are put into line[4096] and I want to copy the elements in line to filebuf. The problem is that I want filebuf to be exactly as big as the amount of elements line contains.

This is because some BMP files might be bigger.

The current BMP file I'm using is only 715 bytes, which means about 3000 bytes are useless data.

Anyone knows how to solve my problem?

2
  • I don't know the limitations of that system, so malloc may not be an option. In that case you would probably want to use a Variable Length Array (available in C99) or whatever your platforms equivalent of alloca is (dynamically allocating stack space) Commented Jul 28, 2020 at 9:04
  • 1
    You might be able to use variable length arrays (VLA), depending on the C standard or the implementation of your compiler. If your target is an embedded system with limited memory it may be better to always use a fixed worst-case buffer size. This makes sure that you will notice the problem when you reach the memory limit. With variable size buffers you might get errors that occur only in certain situations. Commented Jul 28, 2020 at 9:10

1 Answer 1

1

You can use malloc function to dynamically allocate buffer size in exact size as file size.

Here is pseudo code:

char* buff = malloc(buffer_size);

You can use this answer to get a file's size.

But don't forget to free memory after usage.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.