DEV Community

Wakeup Flower
Wakeup Flower

Posted on

C malloc size calculate

Type sizeof(type) Description
char 1 byte Smallest addressable unit (usually ASCII)
short 2 bytes Short integer
int 4 bytes Standard integer
long 8 bytes Long integer (64-bit systems)
long long 8 bytes Guaranteed at least 64 bits
float 4 bytes Single-precision floating point
double 8 bytes Double-precision floating point
long double 16 bytes Extended precision (platform-dependent)
void * 8 bytes Generic pointer (on 64-bit systems)
int * 8 bytes Pointer to int (same size as all pointers)
char str[] = "hello";
printf("%zu\n", strlen(str));   // prints 5
printf("%zu\n", sizeof(str));   // prints 6 (5 letters + '\0')
Enter fullscreen mode Exit fullscreen mode

mistake

char *str = "hello";
printf("%zu\n", sizeof(str));   // prints 8 (on 64-bit, size of pointer)
printf("%zu\n", strlen(str));   // prints 5 (number of chars)

Enter fullscreen mode Exit fullscreen mode

2D Char array static

#include <stdio.h>

int main() {
    char grid[3][5] = {
        "cat",
        "dog",
        "bat"
    };

    int i = 0;
    while (i < 3) {
        printf("Row %d: %s\n", i, grid[i]);
        i++;
    }

    return 0;
}

Enter fullscreen mode Exit fullscreen mode

2D Char array dynamic

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char **alloc_grid(int rows, int cols) {
    char **grid = malloc(rows * sizeof(char *));
    int i = 0;
    while (i < rows) {
        grid[i] = malloc((cols + 1) * sizeof(char));  // +1 for '\0'
        i++;
    }
    return grid;
}

void free_grid(char **grid, int rows) {
    int i = 0;
    while (i < rows) {
        free(grid[i]);
        i++;
    }
    free(grid);
}

int main() {
    int rows = 3, cols = 4;
    char **grid = alloc_grid(rows, cols);

    strcpy(grid[0], "cat");
    strcpy(grid[1], "dog");
    strcpy(grid[2], "bat");

    int i = 0;
    while (i < rows) {
        printf("Row %d: %s\n", i, grid[i]);
        i++;
    }

    free_grid(grid, rows);
    return 0;
}

Enter fullscreen mode Exit fullscreen mode

if you know your string to be stocked, you can do this too
const char *word = "hello";
grid[i] = malloc(strlen(word) + 1); // +1 for '\0'
strcpy(grid[i], word);

important info : pefer sizeof(*ptr) Over sizeof(type)

πŸ” Explanation
Using sizeof(*ptr) makes your malloc() calls more flexible and less error-prone, especially if you change the type later.

🚫 Less flexible / hardcoded type:

int *arr = malloc(10 * sizeof(int));

If you later change arr to a double *, and forget to update sizeof(int), you're in trouble.

βœ… Better: use sizeof(*arr)

int *arr = malloc(10 * sizeof(*arr));

Now, if you change the type of arr to double *, the sizeof part still works correctly without changing anything else:

double *arr = malloc(10 * sizeof(*arr)); // Automatically now uses sizeof(double)

Form Safer? Why
sizeof(type) ❌ You must manually update if type changes
sizeof(*ptr) βœ… Auto-adjusts with pointer type

How to return a 1D int array properly

You can't return a int array directly, ❌ BIG mistake! arr is local β€” memory is destroyed

solution 1 return it in using malloc

int* getArray() {
    int *arr = malloc(5 * sizeof(*arr));
    if (!arr) return NULL;

    int i = 0;
    while (i < 5) {
        arr[i] = i + 1;
        i++;
    }

    return arr;  // βœ… safe: memory is on the heap
}

//in main 

int *myArray = getArray();
if (myArray) {
    // use it
    free(myArray);  // don't forget to free!
}

Enter fullscreen mode Exit fullscreen mode

solution 2 return it by void function without malloc

void fillArray(int *arr, int size) {
    int i = 0;
    while (i < size) {
        arr[i] = i + 1;
        i++;
    }
}

// In main:
int arr[5];
fillArray(arr, 5);

Enter fullscreen mode Exit fullscreen mode

Top comments (0)