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?

Puck
  • 2,080
  • 4
  • 19
  • 30
Jimp0
  • 11
  • 3
  • 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) – UnholySheep Jul 28 '20 at 09: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. – Bodo Jul 28 '20 at 09:10

1 Answers1

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.

Elbek
  • 616
  • 1
  • 4
  • 15