DEV Community

Wakeup Flower
Wakeup Flower

Posted on

malloc and protections

Feature String Literal malloc'd String
Memory Location Read-only segment (.rodata) Heap
Allocated by Compiler You (via malloc)
Lifetime Entire program Until you free() it
Writable? No — writing to it is undefined behavior Yes, you can modify it
Example char *s = "abc"; char *s = malloc(4);
Method Writable? Memory type
char *s = "text"; ❌ No Read-only (literal)
char s[] = "text"; ✅ Yes Stack
char *s = malloc... ✅ Yes Heap

Use stack memory

#include <stdio.h>

int main() {
    char str[] = "Hello,world!";  // Copy of the string literal in writable memory

    str[5] = '_';  // Safe modification
    printf("%s\n", str);  // Output: Hello_world!
    return 0;
}

Enter fullscreen mode Exit fullscreen mode

Use malloc heap memory

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

int main() {
    const char *literal = "Hello,world!";
    char *str = malloc(strlen(literal) + 1);  // +1 for null terminator

    if (str == NULL) {
        perror("malloc failed");
        return 1;
    }

    strcpy(str, literal);  // Copy to heap
    str[5] = '_';  // Safe modification
    printf("%s\n", str);  // Output: Hello_world!

    free(str);  // Always free heap memory when done
    return 0;
}

Enter fullscreen mode Exit fullscreen mode

Null check conditions

return null if its a function

It depends the function is char or void or int

char *allocate_string(size_t size) {
    char *str = malloc(size);
    if (str == NULL) {
        return NULL;  // let the caller handle the error
    }
    return str;
}

int some_function(char *ptr) {
    if (ptr == NULL) {
        return -1;  // error code
    }
    // do work
    return 0;  // success
}

void some_function(char *ptr) {
    if (ptr == NULL) {
        // Maybe print error or just return silently
        return;
    }
    // do stuff
}

Enter fullscreen mode Exit fullscreen mode

in main

int main() {
    char *str = malloc(100);
    if (str == NULL) {
        perror("malloc failed");
        return 1;  // return non-zero to indicate failure
    }
    // ...
    free(str);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

risky crashing

if (str == NULL) {
    perror("malloc failed");
    exit(EXIT_FAILURE);  // from stdlib.h
}
Enter fullscreen mode Exit fullscreen mode

function pointer

void hello(const char *name) {
    printf("Hello, %s!\n", name);
}

void call_with_name(void (*func)(const char *), const char *name) {
    func(name);  // Call the function with the name
}

int main() {
    call_with_name(hello, "Alice");     // ✅ OK
    call_with_name(&hello, "Bob");      // ✅ Also OK
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)