How Computer Memory Works (C version) || Transitioning from Full-stack to System Programming

MEMORY RESEARCH FOR C LANGUAGE:

In my study, I noticed a “char” consumes 1byte (8 bits) in C language, while a “char” cost 4 bytes in Rust (24 bits). The reason for this is, the “char” data type in Rust supports unicode which is 4 byte (an example of unicode is: emoji 😊).

Also, I noticed that when I allocate a memory using malloc, the minimum allocated size I get is 8 bytes even for a char data type that is meant to be 1 byte. Here is what the code looked like:

#include<stdio.h>
#include<stdlib.h>
int main() {char *p = malloc( sizeof(char) * 4); // each char is 1 bytep[0] = ‘h’;p[1] = ‘e’;p[2] = ‘l’;p[3] = ‘l’;p[4] = ‘o’;printf(“P is %s \n”, p);printf(“Total size allocated to p is: %ld \n”, sizeof(p));printf(“Total size allocated to char is: %ld \n”, sizeof(char));return 0;}RESULT:
P is hello
Total size allocated to p is: 8
Total size allocated to char is: 1

Then I decided to declare a char variable and pass the word “hello” to it without using malloc to pre-allocate the memory and it allocated exactly 5 bytes as expected.

#include<stdio.h>#include<stdlib.h>
int main() {char t[5] = {'h', 'e', 'l', 'l', 'o'};printf("T is %s \n", t);printf("Total size allocated to T is: %ld \n", sizeof(t));return 0;}RESULT:
T is hello
Total size allocated to T is: 5

I made a little research and got to understand that malloc pads your data and also allocates a little more for book-keeping. This is the reason my computer memory used 8 bytes instead of 5 bytes to store the text “hello”.

In the course of my research for the issue above I discovered something strange. So someone asked a question:

The code requested malloc to allocate 2 bytes and assigned the memory to the variable “buffer” (don’t forget char consumes 1 byte in the memory). The questioner was surprised that even when he copied the string text “hello” to the memory allocated to the buffer variable (meant to accept a max of 2 bytes), the buffer variable still accepted the string that used 5 bytes.

A response to the question

I discovered that in as much as this works, it is a very bad practise and can result in unexpected results. The moment you allocate just 2 bytes to a string and write data worth more than 2 bytes, you have eaten into another memory you don’t own and this can result in data corruption.

An entrepreneur in the day || Software Engineer at night || I solve problems for a living.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store