Fmstrat
Fmstrat

Reputation: 1692

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

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!

Upvotes: 2

Views: 10630

Answers (2)

Mark Tolonen
Mark Tolonen

Reputation: 177516

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;
}

Upvotes: 6

John Carter
John Carter

Reputation: 55271

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).

Upvotes: 6

Related Questions