Skip to content

Instantly share code, notes, and snippets.

@joegasewicz
Last active November 26, 2022 02:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joegasewicz/03fbfaa795b1351d3ddac3d62f81a960 to your computer and use it in GitHub Desktop.
Save joegasewicz/03fbfaa795b1351d3ddac3d62f81a960 to your computer and use it in GitHub Desktop.
Dynamic Memory Allocation in C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
/* ====================================================================== */
/* Dynamic Memory Allocation */
/* ====================================================================== */
char *str = NULL;
/* Initial memory allocation */
str = (char*)malloc(4 * sizeof(char));
strcpy(str, "joe");
printf("String = %s, Address = %u\n", str, str);
/* Reallocating memory */
str = (char*)realloc(str, 4 * sizeof(char));
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str);
free(str);
char *msg = NULL;
int limit = 0;
printf("Enter the limit:");
scanf("%d", &limit);
msg = (char *)malloc(limit * sizeof(char));
if (!msg)
{
return -1;
}
printf("Enter the string:");
scanf(" ");
gets(msg);
printf("result = %s\n", msg);
free(msg);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment