How to malloc inside a function and return pointer

2019-01-12 08:06发布

问题:

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!

回答1:

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



回答2:

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


回答3:

I am also studying c++. I had a the same question. So after speaking to c++ pro at work, he suggest me to do something like this

int method(char* p) {                 
  if (p) {
    strcpy(p, "I like c++");
  }
  return strlen("I like c++");
}

int main()
{
      char* par = NULL;
      int len = method(par);

      if (len > 0) {
          par = (char*)malloc(len+1);
          memset(par, 0, len + 1);
          method(par);
          cout << "ret : " << par;
      }

      free(par);
}