0

I have been trying to get pointers to work with a structure that I am trying to implement on a PIC. I have tried the same code on a Linux compiler and it works fine. I have also tried stripping it back to basics, but to no avail. Also, I have tried this without pointers and it works.

Here is the code I am using:

struct circular_buf{
    size_t tail;
    size_t head;
    size_t max;
};
    
struct circular_buf * cbuf;

And within the main

cbuf = malloc(sizeof(struct circular_buf));

cbuf->tail = 22;
cbuf->head = 45;
cbuf->max =99;

When I print this out it only prints max out correctly. However, when I insert items to separate the max, tail, and head in the structure it works fine.

struct circular_buf{
    size_t spacer1; // seperatating the items so it reads correctly 
    size_t tail;
    size_t spacer2; // seperatating the items so it reads correctly 
    size_t head;
    size_t spacer3; // seperatating the items so it reads correctly 
    size_t max;
};

Why is this and is there anything I can do to correct this memory error without doing this?

DARTH
  • 1
  • 1
  • 3
    This is not enough info. Please provide a [minimal verifiable example](https://stackoverflow.com/help/minimal-reproducible-example). – kaylum Sep 17 '20 at 11:25
  • `struct * circular_buf` Is that a typo? – Gerhardh Sep 17 '20 at 11:35
  • `sizeof(struct circular_buf_t)` There is no type `struct circular_buf_t` in the snippets you show. Please don't rewrite some new code from memory. Instead copy&paste the real code. The same (complete) thing that you feed into your compiler. – Gerhardh Sep 17 '20 at 11:36
  • @Gerhardh sorry you're right. I have made the corrections – DARTH Sep 17 '20 at 12:02
  • 1
    Good, now let's work on the part related to "complete verifiable example" instead of unrelated snippets .... – Gerhardh Sep 17 '20 at 12:05
  • Read about structure padding and packing: https://stackoverflow.com/questions/4306186/structure-padding-and-packing – paladin Sep 17 '20 at 18:02
  • Which pic compiler are you using xc8, xc16 or xc32? – cup Sep 19 '20 at 08:20
  • @cup I am using MPLAB XC16 – DARTH Sep 21 '20 at 10:30
  • How exactly are you printing out the values - examining values in debug or some other technique. – cup Sep 21 '20 at 21:36
  • @cup I am sending the structure values to a terminal through UART - I have tried this through simple printf statements as well as transmitting them through the UxTXREG. For both methods, I get the same result. – DARTH Sep 22 '20 at 15:03
  • Which version of XC16 are you using? I haven't tried the latest but it works on 1.30. As Gerhardh says, can you post a complete example that doesn't work. – cup Sep 22 '20 at 15:09

0 Answers0