Home > front end >  Allocating Memory to char Pointers for Writing
Allocating Memory to char Pointers for Writing

Time:03-28

So, I'm trying to write into a buffer declared within the main function by allocating memory in the function in which I'm going to write to it, I noticed that passing a char pointer the memory is allocated but can only be used locally, while passing a pointer that points to a char pointer the allocated memory is "visible" even inside the main function.

This is the code where I allocate memory in the heap to the two pointers:

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

void AllocateMemoryToPtr(char* ptr)
{
    if (!(ptr = malloc(32)))
        exit(1);
}

void AllocateMemoryToDoublePtr(char** ptr)
{
    if (!(*ptr = malloc(32))) 
        exit(1);
}

int __cdecl main(void)
{
    char* Ptr = NULL;
    char* DoublePtr = NULL;
    
    printf("\n");
    printf("Ptr\t\tADDRESS\t\tBEFORE\tmalloc\t-> %p\n", Ptr);
    printf("Ptr\t\tVALUE\t\tBEFORE\tmalloc\t-> %s\n", Ptr);
    printf("\n");
    printf("DoublePtr\tADDRESS\t\tBEFORE\tmalloc\t-> %p\n", DoublePtr);
    printf("DoublePtr\tVALUE\t\tBEFORE\tmalloc\t-> %s\n", DoublePtr);
    printf("\n");

    AllocateMemoryToPtr(Ptr);
    AllocateMemoryToDoublePtr(&DoublePtr);

    printf("\n");
    printf("Ptr\t\tADDRESS\t\tAFTER\tmalloc\t-> %p\n", Ptr);
    printf("Ptr\t\tVALUE\t\tAFTER\tmalloc\t-> %s\n", Ptr);
    printf("\n");
    printf("DoublePtr\tADDRESS\t\tAFTER\tmalloc\t-> %p\n", DoublePtr);
    printf("DoublePtr\tVALUE\t\tAFTER\tmalloc\t-> %s\n", DoublePtr);
    printf("\n");

    return 0;
}

Can anyone clarify my ideas on how to write in external buffers using pointers please?

CodePudding user response:

C is pass-by-value. That is, function parameters are like function local variables, modifying them does not modify original. To achieve pass-by-reference, you need to pass a pointer to original.


void AllocateMemoryToPtr(char* ptr)
{
    if (!(ptr = malloc(32)))
        exit(1);
}

char* is pointer to char buffer and allows you to modify the buffer, but not what the original pointer points to.

So you have memory leak here, ptr is lost when function returns.


void AllocateMemoryToDoublePtr(char** ptr)
{
    if (!(*ptr = malloc(32))) 
        exit(1);
}

char** is pointer to pointer, and allows you to modify the original pointer (and also the buffer it points to, of course).

So this does what you want.

CodePudding user response:

Another option is to return the addres of the allocated block, like this:

char * AllocateMemoryToPtr(int size)
{
    if (!(char *ptr = malloc(size)))
        exit(1);
    return ptr;
}

and in main:

int size = 32;
char *ptr = AllocateMemoryToPtr(size);
  • Related