Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to malloc inside a function and return pointer in C?

Tags:

c

function

malloc

Below is some psudo, but I'm trying to accomplish this. The problem is as written, it returns a blank pointer.

int testFunction(char *t) {
    int size = 100;
    t = malloc(100 + 1);
    t = <do a bunch of stuff to assign a value>;
    return size;
}

int runIt() {
    char *str = 0;
    int str_size = 0;
    str_size = testFunction(str);
    <at this point, str is blank and unmodified, what's wrong?>
    free(str);
    return 0;
}

This works fine if I have a predefined size, such as char str[100] = "" and I don't try to malloc or free memory afterwords. I need to be able to make the size dynamic though.

I've also tried this, but seem to run into a corrupt pointer somehow.

int testFunction(char **t) {
    int size = 100;
    t = malloc(100 + 1);
    t = <do a bunch of stuff to assign a value>;
    return size;
}

int runIt() {
    char *str = 0;
    int str_size = 0;
    str_size = testFunction(&str);
    <at this point, str is blank and unmodified, what's wrong?>
    free(str);
    return 0;
}

Thanks!

like image 375
Fmstrat Avatar asked Mar 14 '26 12:03

Fmstrat


2 Answers

You're nearly there with the second example, but change

int testFunction(char **t) {
  ...
  t = malloc(100 + 1);

To

int testFunction(char **t) {
  ...
  *t = malloc(100 + 1);

The point being that you're passing in a char**, a pointer to a pointer, so you want to assign the malloc to what that points at (a pointer).

like image 134
John Carter Avatar answered Mar 16 '26 00:03

John Carter


Your test function is just a bit backward. Size should be an input. The allocated pointer should be the output:

char* testFunction(int size) {
    char* p = malloc(size);
    <do a bunch of stuff to assign a value>;
    return p;
}

int runIt() {
    char *str = 0;
    int str_size = 100;
    str = testFunction(str_size);
    <do something>
    free(str);
    return 0;
}

edit

Per comment, making size an output too.

char* testFunction(int *size) {
    *size = <compute size>;
    char* p = malloc(size);
    <do a bunch of stuff to assign a value>;
    return p;
}

int runIt() {
    char *str = 0;
    int str_size;
    str = testFunction(&str_size);
    <do something>
    free(str);
    return 0;
}
like image 22
Mark Tolonen Avatar answered Mar 16 '26 01:03

Mark Tolonen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!