When initializing a struct in C, we can allocate memory inside the main
function or within another function and return a pointer to the newly created struct. This first example shows the latter; memory is allocated in Buffer_create
and a pointer is returned:
#include <stdio.h>
#include "buffer.h"
int main(int argc, char *argv[])
{
struct Buffer *tx_buffer = Buffer_create(8);
Buffer_destroy(tx_buffer);
return 0;
}
And this one shows how all memory allocations can be done within the main
function:
#include <stdio.h>
#include "buffer.h"
int main(int argc, char *argv[])
{
uint8_t *ptr_rx_buffer = malloc(sizeof(uint8_t)*8);
struct Buffer *rx_buffer = malloc(sizeof(struct Buffer));
Buffer2_create(rx_buffer, ptr_rx_buffer, 8);
Buffer2_destroy(rx_buffer);
return 0;
}
And here are the contents of the header file buffer.h
:
#ifndef _buffer_h
#define _buffer_h
#include <stdint.h>
#include <stdlib.h>
struct Buffer {
uint8_t *buffer;
size_t size;
};
struct Buffer *Buffer_create(size_t size);
void Buffer_destroy(struct Buffer *who);
void Buffer2_create(struct Buffer *who, uint8_t *buffer, size_t size);
void Buffer2_destroy(struct Buffer *who);
#endif
And buffer.c
:
#include <stdint.h>
#include <assert.h>
#include <stdlib.h>
#include "buffer.h"
struct Buffer *Buffer_create(size_t size)
{
struct Buffer *who = malloc(sizeof(struct Buffer));
assert(who != NULL);
who->buffer = malloc(sizeof(uint8_t)*size);
who->size = size;
return who;
}
void Buffer_destroy(struct Buffer *who)
{
assert(who != NULL);
free(who->buffer);
free(who);
}
void Buffer2_create(struct Buffer *who, uint8_t *buffer, size_t size)
{
assert(who != NULL);
who->buffer = buffer;
who->size = size;
}
void Buffer2_destroy(struct Buffer *who)
{
assert(who != NULL);
free(who->buffer);
free(who);
}
The Result
Both approaches work and the executable files for both end up being the same size.
My Question
Will either of these approaches result in memory leaks or poor performance?