Home > OS >  Malloc within function not changing pointer value
Malloc within function not changing pointer value

Time:11-03

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.

CodePudding user response:

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.

CodePudding user response:

There are not enough *'s in each place, but you will have to figure out what that means.

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

int main(){
    int* val2;

    allocate(&val2);

    free(val2);

    return 0;
}
  • Related