Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tornikegomareli/325953e7bcb326842e8ae83bee2bc3ed to your computer and use it in GitHub Desktop.
Save tornikegomareli/325953e7bcb326842e8ae83bee2bc3ed to your computer and use it in GitHub Desktop.
C - Own realloc function, and original realloc function. Playing with pointers
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <assert.h>
using namespace std;
void* my_realloc(void *ptr, int originalLength, int newLength)
{
if (newLength == 0)
{
free(ptr);
return NULL;
}
else if (!ptr)
{
return malloc(newLength);
}
else if (newLength <= originalLength)
{
return ptr;
}
else
{
assert((ptr) && (newLength > originalLength));
void *ptrNew = malloc(newLength);
if (ptrNew)
{
memcpy(ptrNew, ptr, originalLength);
free(ptr);
}
return ptrNew;
}
}
int* CreateAllocation(int len) {
int *X = (int*)malloc(len * sizeof(int));
return X;
}
void Add_10(int*ptr,int length)
{
if (ptr != NULL) {
for (size_t i = 0; i < length; i++)
{
*(ptr + i) = i + 1;
}
}
else
cout << " Ptr is NULLPTR ";
}
void Add_20(int*ptr, int length)
{
if (ptr != NULL) {
for (size_t i = 10; i < length; i++)
{
*(ptr + i) = i + 1;
}
}
else
cout << " Ptr is NULLPTR ";
}
void Print(int*ptr, int len) {
for (int i = 0; i < len; i++)
{
cout << *(ptr + i) << " ";
}
}
void Realloc(int** ptr,int len)
{
*ptr = (int*)realloc(*ptr, len * sizeof(int));
}
int main()
{
int len = 10;
int* ptr = CreateAllocation(len);
cout << "Before Realloc " << endl;
Add_10(ptr, len);
Print(ptr, len);
cout << "\n After Realloc " << endl;
Realloc(&ptr, 20);
Add_20(ptr, 20);
Print(ptr, 20);
free(ptr);
getchar();
getchar();
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment