I was writing a simple program to see how dynamic memory allocations in C works.
#include <stdio.h>
#include <stdlib.h>
int main() {
char* c = (char* ) malloc(sizeof(char) * 1);
int* a = (int* ) malloc(sizeof(int) * 1);
for (int i = 0; i < 10; i++)
*(a+i) = i;
c = "Hello World";
printf("%c\n", *(c+4));
printf("%d\n", *(a+4));
return 0;
}
The output I get is
o
4
I've allocated enough memory to save a single character and an integer. But then, how is a whole string and an array of integers of length 10 getting saved?
Does the memory automatically get extended? Could someone kindly explain how it works? Thanks.
In accessing the dynamically allocated array a
out of bounds, you invoke undefined behavior. The program may do anything, including "working" the way you expected.
int* a = (int* ) malloc(sizeof(int) * 1);
for (int i = 0; i < 10; i++)
*(a+i) = i;
I will suggest a different syntax, and that you not cast the result of malloc
.
int* a = malloc(sizeof(int) * 1);
for (int i = 0; i < 10; i++)
a[i] = i;
As for your string:
char* c = (char* ) malloc(sizeof(char) * 1);
c = "Hello World";
You are allocating one byte of memory and c
is pointing to it. You then reassign c
to point to a string literal. As a result, you can print c
without issue. Since the dynamically allocated memory is no longer pointed to, you cannot free
it and a very small memory leak is created.
If you wanted to copy Hello World" into the memory
c` pointed to initially, you'd write:
strcpy(c, "Hello World");
But this would access out of bounds for c
, and we'd be back in the territory of undefined behavior.
Please note that strings in C require a null terminating character at the end. A single char's memory cannot store a string as it only has room for the null terminator.