I am writing a circular/ring buffer of a specified size. I am struggling with figuring out if my code is working. It compiles and runs with no problem, but I try testing it with print statements and I get confused. Can anyone give me some advice for how to test that my code is functioning properly - access up to a defined number of buffers and checks if the buffer is full or empty when requesting the next and freeing the last buffer.

#include <stdio.h>

int head = 0;
int tail = 0;
int num_allocated = 0;

struct s_buffer 
{
	int dummy_val1;
	int dummy_val2;
};
struct s_buffer ring[16];


int increment_head()
{
	if (head >= 16)
	{
		head =0;
		num_allocated ++;
	}
	else
	{
		head ++;
		num_allocated ++;
	}
	
	return head;
	
}

int increment_tail()
{
	if (tail >= 16)
	{
		tail =0;
		num_allocated --;
	}
	else
	{
		tail ++;
		num_allocated --;
	}
	
	return tail;
	
}

struct s_buffer* requestNextBuffer()
{
	if(isBufferFull(tail)) 
	{
		return NULL;
	}
	else
	{
		struct s_buffer* sb = NULL;
		increment_head();
		sb = &ring[head];
		return sb;
	}
}

struct s_buffer* freeLastBuffer()
{
	if(isBufferEmpty(head)) 
	{
		return NULL;
	}
	else
	{
		struct s_buffer* sb = NULL;
		increment_tail();
		sb = &ring[tail];
		return sb;
	}
}

int isBufferEmpty (int increment_head)
{
	if (increment_head <=0)
	{
		return 1;
	}
	else
	{
		return 0;
	}
	
}

int isBufferFull (int tail)
{
	if (head==tail)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

int main (void) 
{
	struct s_buffer *sb;
	do
	{
	
		sb=requestNextBuffer();
		sb->dummy_val1==2;	
	}
	while (sb!=NULL);
	
}

u can write a display function which displays all the values present in the current buffer e.g.

void displayBuffer()
{
      //code to display the contents of the valid buffer//
      //i.e. from head to tail...//
}

u can use this function after any buffer operation such as requestNextBuffer(...) etc.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.