Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Malloc within function not changing pointer value

So when I pass a data type like a struct to assign some memory to it I find that the pointer doesn’t change within the main scope. This further becomes a problem when I try to free the memory but obviously if its using the original pointer it will be pointing at the stack address.

void allocate(int *value){
    value = malloc(10 * sizeof(int));
}

int main(){
    int val2;

    allocate(&val2);

    free(&val2);

    return 0;
}

I can fix this by using a double pointer to be passed into the allocate function but some course work I’m doing requires to only pass a pointer and I cant get it to update the pointer when it returns to main. I have looked around for a while but cant find a straight forward answer, I feel like my coursework is wrong but that might be my lack of understanding.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The requirement to "only pass a pointer" seems contrived, and you could argue that a pointer to pointer (not a "double pointer") is a pointer, but perhaps you could use void * to punch a hole in the type system. Or use a struct:

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

struct intbuffer {
    int *d;
    size_t cap;
};


void *
xmalloc(size_t s)
{
    void *r = malloc(s);
    if( r == NULL ){
        perror("malloc");
        exit(1);
    }
    return r;
}

void
allocate(void *p, size_t s)
{
    *(int **)p = xmalloc(s * sizeof(int));
}

void
allocate2(struct intbuffer *p)
{
    p->d = xmalloc(p->cap * sizeof *p->d);
}


int
main(void){
    int *val2;
    struct intbuffer v;

    allocate(&val2, 10);
    free(val2);

    v.cap = 10;  /* Horrible api!! */
    allocate2(&v);
    free(v.d);

    return 0;
}

Note that setting the capacity in the struct prior to making the call to allocate is a violation of many principles of software design, but this whole thing is absurdly contrived due to the bizarre artificial limitations.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading