Circular Buffer

I have created a program using heap memory to implement circular buffer. The following is the code of the program.

 

// testCircularBuffer.cpp : Defines the entry point for the console application.
//

#include<iostream>

#include “stdio.h”
#include “stdlib.h”
#include “string.h”
#include<Windows.h>

#define LONG int
#define PBYTE char *

#define TRUE 1
#define FALSE 0

static LONG m_ReadHanlde;
static LONG m_WriteHanlle;
static PBYTE pMemBuffer;
static int memBufWrap ;// buffer wrap around

#define MIN_CHUNK_SIZE 1024 * 1024
int CIRCULAR_BUFFER_SIZE = 5 * MIN_CHUNK_SIZE; // size in MB

int InitCircularMemBuffer()
{

pMemBuffer = NULL;
m_ReadHanlde = 0;
m_WriteHanlle = 0;
memBufWrap = 0;

pMemBuffer = (char*) malloc(CIRCULAR_BUFFER_SIZE);
if(pMemBuffer == NULL){
return -1;
}

return 0;
}

int ReleaseCircularMemBuffer()
{

if(pMemBuffer != NULL){
free( pMemBuffer);
pMemBuffer = NULL;
}

return 0;
}

LONG GetCircularMemBufferSpace()
{
LONG lMemDist = 0;

if(pMemBuffer == NULL)
return 0;

//if(m_WritePtr == 0 && m_ReadPtr == 0)
if((m_WriteHanlle == m_ReadHanlde)&& (!memBufWrap))
{

return CIRCULAR_BUFFER_SIZE;
}

if(m_WriteHanlle > m_ReadHanlde)
{
lMemDist = (CIRCULAR_BUFFER_SIZE – m_WriteHanlle) + m_ReadHanlde;
}
else
{
lMemDist = m_ReadHanlde – m_WriteHanlle;
}

return lMemDist;
}

LONG GetCircularMemBufferArea()
{
LONG lmemArea = 0;

if(pMemBuffer == NULL)
return 0;

if(m_WriteHanlle == m_ReadHanlde && (!memBufWrap))
{

return 0;
}

if(m_WriteHanlle > m_ReadHanlde)
{
lmemArea = m_WriteHanlle – m_ReadHanlde;
}
else
{
lmemArea = (CIRCULAR_BUFFER_SIZE – m_ReadHanlde) + m_WriteHanlle;
}

return lmemArea;
}

int ResetCiruclarMemBuffer()
{
int MaxSecondCnt=10,i;

m_ReadHanlde = 0;
m_WriteHanlle = 0;
memBufWrap = 0;

return TRUE;
}

int ReadCircularMemBuffer(PBYTE pBuff, LONG lSize)
{
LONG lDist;

for(;;)
{
if(GetCircularMemBufferArea() >= lSize)
break;
else
{
Sleep(100);

}

}

if( ( m_ReadHanlde + lSize) > CIRCULAR_BUFFER_SIZE )
{
lDist = CIRCULAR_BUFFER_SIZE – m_ReadHanlde;
memcpy(pBuff, (pMemBuffer + m_ReadHanlde), lDist);
memcpy(pBuff + lDist, pMemBuffer, lSize – lDist);
m_ReadHanlde = lSize – lDist;
memBufWrap =0; // read also wrap around
}
else
{
memcpy(pBuff, (pMemBuffer + m_ReadHanlde), lSize);
m_ReadHanlde += lSize;
}

return lSize;
}

int WriteCircularMemBuffer(PBYTE pBuff, LONG lSize)
{
int dwDist;
//printf(“WriteBuffer+\n”);
if(pMemBuffer == NULL)
return FALSE;

//wait for enough space
for(;;)
{
if(GetCircularMemBufferSpace() >= lSize){
break;

}
else
{
Sleep(1);
}
}

if( ( m_WriteHanlle + lSize) > CIRCULAR_BUFFER_SIZE)
{

dwDist = CIRCULAR_BUFFER_SIZE – m_WriteHanlle;
memcpy( (pMemBuffer + m_WriteHanlle), pBuff,dwDist);

memcpy(pMemBuffer, (pBuff + dwDist), lSize – dwDist);
m_WriteHanlle = lSize – dwDist;
memBufWrap = 1;// the buffer just wrap around

return TRUE;
}

memcpy( (pMemBuffer + m_WriteHanlle), pBuff,lSize);
m_WriteHanlle += lSize;

return TRUE;
}

char testWriteBuf[5*MIN_CHUNK_SIZE+1];
char testReadBuf[5*MIN_CHUNK_SIZE+1];

int main()
{

InitCircularMemBuffer();

printf(“Free Mem %d and data size %d in buff m_WriteHandle %d m_ReadHanlde %d\n”,GetCircularMemBufferSpace(),GetCircularMemBufferArea(),m_WriteHanlle,m_ReadHanlde);
if(!WriteCircularMemBuffer(testWriteBuf, MIN_CHUNK_SIZE))
printf(“Write error\n”);
printf(“Free Mem %d and Data size %d avaliable in buff m_WritePtr %d m_ReadPtr %d\n”,GetCircularMemBufferSpace(),GetCircularMemBufferArea(),m_WriteHanlle,m_ReadHanlde);

if(!ReadCircularMemBuffer(testReadBuf, MIN_CHUNK_SIZE))
printf(“Read memory buffer error\n”);

}

Working with memory

I have created a program in which i have handled a memory allocated from heap. In this program i have created a memory of specific size form heap and storing data in it. When the memory is full then i reset it from start and storing data again in the memory. The following is the complete code of the program. 

 

// testMemory.cpp : Defines the entry point for the console application.
//

#include<stdio.h>
#include<iostream>

using namespace std;

char *startOfMemory;
char *pMemory;

int main(void){

pMemory = (char *)malloc(256);
startOfMemory = pMemory;
int countMem = 0;
char *str = strdup(“This is just test msg”);
int len = strlen(str);
int count = 0;
while(count<1000){

if (countMem + len > 256){
pMemory = startOfMemory;
printf(“Mem is full now set to start\n”);
countMem = 0;
}
memcpy(pMemory,str,len);
pMemory = pMemory + len;
countMem = countMem + len;
printf(“Mem Size:%d\n”,countMem);

count = count + 1;
}
pMemory = startOfMemory;

free(pMemory);
pMemory = NULL;

getchar();
return 0;
}

Encoding and decoding of Struct

I have created a program in which i have encode and decode the struct. This is required when sending data using network. The following is the code of the program.

// testStructEnDec.cpp : Defines the entry point for the console application.
//

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>

using namespace std;

typedef struct ipV4{
char *strIP;
}tIpV4;

typedef struct IPList{
int num;
int port;
tIpV4 objIPList[20];
}tRemoteIPList;

size_t encodeRemoteIP(tRemoteIPList* objIPList, unsigned char** buf);
tRemoteIPList* decodeIP(const unsigned char* buf, const size_t bufSize);

int main(void){
tRemoteIPList objList;

objList.num = 3;
objList.port = 80;
objList.objIPList[0].strIP = strdup(“192.168.1.1”);
objList.objIPList[1].strIP = strdup(“192.168.1.2”);
objList.objIPList[2].strIP = strdup(“192.168.1.10”);
unsigned char *buf;
size_t bufSize = encodeRemoteIP(&objList,&buf);

tRemoteIPList* objIP = decodeIP(buf,bufSize);
printf(“Port:%d”,objIP->port);
for(int count = 0;count<objIP->num;count++){
printf(“IP:%s\n”,objIP->objIPList[count].strIP);

}

getchar();
return 0;
}

size_t encodeRemoteIP(tRemoteIPList* objIPList, unsigned char** buf)
{
int count;
size_t total_size = 0;
if (!objIPList)
{
return 0;
}
total_size = total_size + sizeof(size_t) + sizeof(size_t); // no of ips.

for(count = 0;count<objIPList->num;count++){
total_size = total_size + strlen(objIPList->objIPList[count].strIP) + sizeof(size_t)+sizeof(size_t);
}

*buf = (unsigned char *)calloc(1,total_size);
if (*buf)
{
size_t offset = 0;
size_t ipLen;
size_t numIp = htonl(objIPList->num);
size_t port = htonl(objIPList->port);

memcpy(*buf + offset, &numIp,sizeof(numIp)); offset += sizeof(numIp);
memcpy(*buf + offset, &port,sizeof(port)); offset += sizeof(port);
for(count = 0;count<objIPList->num;count++){
ipLen = strlen(objIPList->objIPList[count].strIP);
ipLen = htonl(ipLen);
memcpy(*buf + offset, &ipLen,sizeof(size_t)); offset += sizeof(ipLen);
memcpy(*buf + offset, objIPList->objIPList[count].strIP,ipLen); offset += ipLen;
}
}

return total_size;

}

tRemoteIPList* decodeIP(const unsigned char* buf, const size_t bufSize)
{
tRemoteIPList *objIP;

if(buf!= NULL){
objIP = (tRemoteIPList *)calloc(1, sizeof(tRemoteIPList));

if(objIP !=NULL){
size_t numIP = 0;
size_t port;
size_t offset = 0;
size_t ipLen;
unsigned int count = 0;
memcpy(&numIP, buf + offset, sizeof(numIP));
numIP = ntohl(numIP);
offset += sizeof(numIP);
objIP->num = numIP;

memcpy(&port, buf + offset, sizeof(port));
port = ntohl(port);
offset += sizeof(port);
objIP->port = port;

for(count = 0;count<numIP;count++){
memcpy(&ipLen, buf + offset, sizeof(ipLen));
ipLen = ntohl(ipLen);
offset += sizeof(ipLen);
objIP->objIPList[count].strIP = (char *)calloc(1,ipLen + 1);
memcpy(objIP->objIPList[count].strIP,buf+offset,ipLen);
offset +=ipLen;

}

}
}

return objIP;
}

Array of Pointer to Pointer

I have created a program in which i have used array of pointer to pointers. The following is the complete code. 

// testArrayOfPointers.cpp : Defines the entry point for the console application.
//

#include<conio.h>
#include<iostream>

using namespace std;

typedef unsigned char ** arrayofPointerToPointer[5];

arrayofPointerToPointer pointerToPointerList;
unsigned char **pPointerArray;

int main(void){

for(int count = 0;count<5;count++){
pointerToPointerList[count] = NULL;
}
pPointerArray = (unsigned char **)malloc(5 * sizeof(unsigned char **));
pointerToPointerList[0] = pPointerArray;
char *strName1 = strdup(“Jawad1”);
char *strName2 = strdup(“Jawad2”);
char *strName3 = strdup(“Jawad3”);
char *strName4 = strdup(“Jawad4”);
pPointerArray[0] = (unsigned char*)strName1;
pPointerArray[1] = (unsigned char*)strName2;
pPointerArray[2] = (unsigned char*)strName3;
pPointerArray[3] = (unsigned char*)strName4;

unsigned char **pTempPointerArray = pointerToPointerList[0];

for(int i=0;i<4;i++){
printf(“My name:%s\n”,pTempPointerArray[i]);
}

getchar();
return 0;
}

 

Array and pointers

I have created a program in  which i have worked with arrays like 1 dim, 2 dim and 3 dim . In this program i have accessed elements of array using different methods. The program is as follows.

// testArrays.cpp : Defines the entry point for the console application.
//

#include<stdio.h>
#include<iostream>

int main(void){

//single dimension array
int a[5] = {1,2,3,4,5};
//pointer to store the starting address of array
int *ptr;
ptr = a;
//a[1] or *(a + 1) — 1 read operation
//ptr[1] or *(ptr + 1)—2 read operation
printf(“1st element a[1]:%d and prt:%d\n”,a[1],*(ptr +1)) ;

//two dimension array
int a2d[2][5] = {{1,2,3,4,5},{5,6,7,8,9}};
//pointer to two dimesnion array.
int (*ptr2D)[5];

ptr2D = a2d;

printf(“a2d[1][4]:%d *(*(a2d+1)+4):%d\n”,a2d[1][4],*(*(a2d+1)+4));
printf(“dim-ptr2D[1][4]:%d *(*(ptr2D+1)+4):%d\n”,ptr2D[1][4],*(*(ptr2D+1)+4));

//three dimenison array
int a3D[2][3][4] = { { {1, 2, 3, 4}, {4, 5, 6, 7}, {8, 9, 10,11} },
{ {12, 13, 14, 15}, {16, 17, 18, 19}, {20, 21, 22, 23} } };

int (* ptr3D)[3][4];
ptr3D = a3D;

printf(“a3D[1][2][3]:%d *(*(*(a3D+1)+2)+3):%d\n”,a3D[1][2][3], *(*(*(a3D+1)+2)+3));
printf(“ptr3D[1][2][3]:%d *(*(*(ptr3D+1)+2)+3):%d\n”,ptr3D[1][2][3], *(*(*(ptr3D+1)+2)+3));

//pointer to three dimensional array

getchar();
}

 

Low and Hi Word modificaion

I have created a program in which I have modified the Low Word and High Word of integer. Then these low and high words are obtained from integer type. The following is the code of program.

// testTypeManipulation.cpp : Defines the entry point for the console application.
//

#include<stdio.h>
#include<iostream>

int replaceLowWordFromInt(int x, int n, int c) {
int mask = 0xffff << (n << 3);
int shift = (c << (n << 3));
return (~mask & x) | shift;
}

int replaceHiWordFromInt(int x, int n, int c) {
x = (x & 0xFFFF) | (c << 16);
return x;
}

short getLowWordFromInt(int value)
{

return (value & 0xFFFF);
}

short getHiWordFromInt(int value)
{
return ((value & 0xFFFF0000)>>16);
}

int main(void){

int Lowval = 500;
int Hival = 600;
int data = 0;
short lowWord;
short hiWord;
//Modificaion in LO and HI Word of integer.
data = replaceLowWordFromInt(data,0,Lowval);
data = replaceHiWordFromInt(data,0,Hival);
printf(“After modificaion:%d\n”,data);
lowWord = getLowWordFromInt(data);
hiWord = getHiWordFromInt(data);
printf(“Low Word:%d and High Word:%d\n”,lowWord,hiWord);
int combine = ((hiWord<<16) | ((lowWord) & 0xffff));
printf(“Combine :%d\n”,combine);
getchar();
return 0;
}

 

Network Info Application (Ethernet Card)

I have created an application which obtains the network interface information like IP address assigned to the card, interface friendly name and it is currently connected with the network or not.  The code is as follows;

// testLANInfo.cpp : Defines the entry point for the console application.
//

#include<stdio.h>
#include<iostream>
#include <vector>
#include <winsock2.h>
#include <iphlpapi.h>

#pragma comment(lib, “IPHLPAPI.lib”)
using namespace std;

#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))

typedef struct networkInterfaceDetails{
string interfaceName;
string strIP;
int isConnectedOrDisConnected;
}tNetworkInterfaceDetails;

int getNetworkInterfaceInfo(vector<tNetworkInterfaceDetails *> &objInterfaceDetails)
{
DWORD dwSize = 0;
DWORD dwRetVal = 0;

unsigned int i = 0;
// Set the flags to pass to GetAdaptersAddresses
ULONG flags = GAA_FLAG_INCLUDE_PREFIX;

// default to unspecified address family (both)
ULONG family = AF_UNSPEC;

LPVOID lpMsgBuf = NULL;

PIP_ADAPTER_ADDRESSES pAddresses = NULL;
ULONG outBufLen = 0;

PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL;
family = AF_INET;

outBufLen = sizeof (IP_ADAPTER_ADDRESSES);
pAddresses = (IP_ADAPTER_ADDRESSES *) MALLOC(outBufLen);

// Make an initial call to GetAdaptersAddresses to get the
// size needed into the outBufLen variable
if (GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen)
== ERROR_BUFFER_OVERFLOW) {
FREE(pAddresses);
pAddresses = (IP_ADAPTER_ADDRESSES *) MALLOC(outBufLen);
}

if (pAddresses == NULL) {
//DEBUG(“Memory allocation failed for IP_ADAPTER_ADDRESSES struct\n”);
return 1;
//exit(1);
}

dwRetVal = GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen);

if (dwRetVal == NO_ERROR) {
// If successful, output some information from the data we received
pCurrAddresses = pAddresses;
while (pCurrAddresses) {

switch (pCurrAddresses->IfType) {
case IF_TYPE_ETHERNET_CSMACD:
{
char conBuffer[100];
int ret;
string conStr;
string IPstr;
ret = wcstombs ( conBuffer, pCurrAddresses->FriendlyName, sizeof(conBuffer) );
tNetworkInterfaceDetails *objEthernetInfo = new tNetworkInterfaceDetails;
objEthernetInfo->interfaceName = conStr;
objEthernetInfo->strIP = IPstr;

switch (pCurrAddresses->OperStatus) {
case IfOperStatusUp:
objEthernetInfo->isConnectedOrDisConnected = 1;
break;
case IfOperStatusDown:
objEthernetInfo->isConnectedOrDisConnected = 0;
break;
default:
objEthernetInfo->isConnectedOrDisConnected = 0;
}

objInterfaceDetails.push_back(objEthernetInfo);
break;
}

pCurrAddresses = pCurrAddresses->Next;
}
}
}else {
if (dwRetVal == ERROR_NO_DATA)
return 1;
else {

if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwRetVal, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) & lpMsgBuf, 0, NULL)) {
LocalFree(lpMsgBuf);
FREE(pAddresses);
return 1;
}
}
}

FREE(pAddresses);

return 0;

} //end getNetworkInterfaceInfo

int main(void){

vector<tNetworkInterfaceDetails *> objInterfaceInfo;
getNetworkInterfaceInfo(objInterfaceInfo);

for(int countInterfaces = 0;countInterfaces<objInterfaceInfo.size();countInterfaces++){
tNetworkInterfaceDetails *objInfo = (tNetworkInterfaceDetails *)objInterfaceInfo.at(countInterfaces);

printf(“Interface Friendly name:%s\n”,objInfo->interfaceName);
printf(“Interface IP:%s\n”,objInfo->strIP);
printf(“Connection Status:”);
if(objInfo->isConnectedOrDisConnected == 1){
printf(“Connected\n”);
}
else{
printf(“Not Connected\n”);
}
}
getchar();
return 0;
}