0

Below is minimal, reproducible code for my problem. I don't know why this piece of code prints 1 as I expect to print 512.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct ser_buff_ {
  #define SERIALIZE_BUFFER_DEFAULT_SIZE 512
  void *b;
  int size;
  int next;
}ser_buff_t;

void
init_serialized_buffer(ser_buff_t *b){
  b = (ser_buff_t*)calloc(1, sizeof(ser_buff_t));
  b->b  = calloc(1, SERIALIZE_BUFFER_DEFAULT_SIZE);
  b->size = SERIALIZE_BUFFER_DEFAULT_SIZE;
  b->next = 0;
}

int main(void){
  ser_buff_t *b;
  init_serialized_buffer(b);
  printf("%d\n", b->size);
    return 0;
}
Ben Eslami
  • 70
  • 8
  • See [**How to change value of variable passed as argument?**](https://stackoverflow.com/questions/9459691/how-to-change-value-of-variable-passed-as-argument) I'll let others decide if this is a dupe of that question (or any other question...) – Andrew Henle Apr 10 '20 at 14:05
  • No @UnholySheep – Ben Eslami Apr 10 '20 at 14:10
  • How not? Your function does not modify `b` in main, so when you call `printf("%d\n", b->size);` you invoke *undefined behavior* - see the dupe for how to fix it – UnholySheep Apr 10 '20 at 14:11

1 Answers1

1

@UnholySheep is right. You need to pass the reference to the first pointer in the init_serialized_buffer() in order to be able to modify it.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct ser_buff_ {
    #define SERIALIZE_BUFFER_DEFAULT_SIZE 512
    void *b;
    int size;
    int next;
}ser_buff_t;

void
init_serialized_buffer(ser_buff_t **b){
    *b = (ser_buff_t*)calloc(1, sizeof(ser_buff_t));
    (*b)->b  = calloc(1, SERIALIZE_BUFFER_DEFAULT_SIZE);
    (*b)->size = SERIALIZE_BUFFER_DEFAULT_SIZE;
    (*b)->next = 0;
}

int main(void){
    ser_buff_t *b;
    init_serialized_buffer(&b);
    printf("%d\n", b->size);
    return 0;
}
throwaway
  • 11
  • 1