0

I am trying to write a small function that calculates difference for each pixel. However, seems like casting int to uint8_t ( (uint8_t)temp ) is causing problems on a microprocessor at the very first iteration and leads to a restart


abs_diff = (uint8_t*)malloc(320*240 * sizeof(uint8_t));

for (int i = 0; i < 320*240; i++){
    int temp = abs((int)_jpg_buf[i] - (int)_jpg_buf_prev[i]);
    Serial.printf("abs %d\n", temp);
    abs_diff[i] = (uint8_t)temp; // <- fails
}

P.S. not a C expert here

Boris
  • 1
  • 2
  • Look here: https://stackoverflow.com/questions/44892781/ – DipStax Nov 16 '20 at 22:19
  • @DipStax That's the opposite direction. – John Kugelman Nov 16 '20 at 22:19
  • 5
    Are you sure malloc succeded? – Mat Nov 16 '20 at 22:19
  • Really really recommend you don't use magic numbers like this. Add a `#define NUM_ITEMS (320*240)` up at the top, and then use that macro in both places. It's super easy to need to change this for whatever reason, but forget to change them *both*. – Steve Friedl Nov 16 '20 at 22:22
  • @Mat you are right, malloc failed.. Never seen malloc fail before on PCs... – Boris Nov 16 '20 at 22:32
  • 2
    `malloc` is unlikely to fail on a PC. But there are a number of reasons why `malloc` might fail on an embedded platform. First and foremost is that `malloc` simply isn't supported. Try `malloc(8)`. If that fails, then you don't have any support for `malloc`. If it succeeds, the next question is how much memory is available. 320*240 is about 80KB. That's nothing for a PC, but could be too much for embedded. – user3386109 Nov 16 '20 at 22:39
  • 1
    Should `int` be 16-bit, `320*240` overflows regardless of `size_t`. `sizeof(uint8_t)*320*240` is better when `size_t` > 16-bit as the multiplication uses wdier `size_t` math. – chux - Reinstate Monica Nov 16 '20 at 22:49
  • 1
    Boris what is the size of `int` or what is `INT_MAX`? – chux - Reinstate Monica Nov 16 '20 at 22:52
  • are you on Arduino? It's not C because C doesn't support `Serial.printf` unless Serial is a struct with a function pointer member – phuclv Nov 17 '20 at 00:23

0 Answers0