Home > Software engineering >  How do I return a string from a function?
How do I return a string from a function?

Time:10-15

Usually I develop in PHP. But for a project I have to develop a small program in C (using Visual Studio on Windows) To simplify my code I created a function that returns a string (the function is more complex than in the example).

Initially I had a warning C4172: returning address of local variable or temporary [duplicate] I modified my function to no longer have this warning. And it works. But is the code right...?

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

// Declaration Function
char* getMyString();

//----------------------------//
// Function getMyString()     //
//----------------------------//
char* getMyString()
{
  char* response = NULL;
  response = (char*)malloc(5 * sizeof(char)); if (response == NULL) exit(EXIT_FAILURE);

  strcpy(response, "EFGH");

  return response;
}



//--------------------------------------------------//
//                    Main Program                  //
//--------------------------------------------------//
int main(int nbArg, char** listeArg)
{
  // Initialization
  char* myStringFull = malloc(10 * sizeof(char)); if (myStringFull == NULL) return EXIT_FAILURE;
  char* myString = NULL;

  // Get String with Personnal Function
  myString = getMyString();

  // Finalization
  strcpy(myStringFull, "ABCD");
  strcat(myStringFull, myString);

  // Display
  printf("\n%s\n\n", myStringFull);

  // Free Memory
  free(myStringFull);
  free(myString);

  return(EXIT_SUCCESS);
}

And if above code is right, can I use the code below to further simplify my code...? And if I can how it happens in memory because for this last code I can not free the memory used by the function

int main(int nbArg, char** listeArg)
{
  // Initialization
  char* myStringFull = malloc(10 * sizeof(char)); if (myStringFull == NULL) return EXIT_FAILURE;

  // Finalization
  strcpy(myStringFull, "ABCD");
  strcat(myStringFull, getMyString());

  // Display
  printf("\n%s\n\n", myStringFull);

  // Free Memory
  free(myStringFull);


  return(EXIT_SUCCESS);
}

Hope my question isn't too silly but there is a big, huge, abyssal gap between PHP and C :)

CodePudding user response:

What you did is correct. However, you've noticed that it's quite a bit of work, and you have to remember to free the allocated memory afterwards. If possible, I would use C so you can return a std::string without worries, much like you would do in PHP and many other languages.

There are other functions that might help you create strings in C. For example, copying strings can be done by the POSIX function strdup(). You can also use asprintf() on GNU and BSD platforms.

Instead of allocating memory, you could also print into a buffer. To do that from a function, you would pass a pointer to the buffer and its size to that function. For example:

void getMyString(char *buf, size_t size) {
    snprintf(buf, size, "EFGH");
}

int main(int argc, char *argv[]) {
    char myStringFull[10];
    int pos = snprintf(myStringFull, sizeof myStringFull, "ABCD");
    getMyString(myStringFull   pos, sizeof myStrinfFull - pos);
    printf("%s\n", myStringFull);
}

Note that the above is still missing error checking; the return value of snprintf() is the number of characters that would have been written if the buffer was large enough, or possibly a negative number indicating an error.

CodePudding user response:

The pointer and size of the allocation can be passed to the function.
The function can reallocate the pointer as necessary, concatenate then return the pointer.
The calling function can free the pointer without memory leak even if it has been reallocated.

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

// Declaration Function
char* getMyString( char *str, size_t size);

//----------------------------//
// Function getMyString()     //
//----------------------------//
char* getMyString( char *str, size_t size)
{
    char response[] = "EFGH";
    size_t len = strlen ( str);
    size_t length = strlen ( response);
    if ( len   length   1 >= size) {
        char *temp = NULL;
        if ( NULL == ( temp = realloc( str, len   length   1))) {
            fprintf ( stderr, "problem realloc\n");
            exit(EXIT_FAILURE);
        }
        str = temp;
    }

    strcat (str, response);

    return str;
}

//--------------------------------------------------//
//                    Main Program                  //
//--------------------------------------------------//
int main(int nbArg, char** listeArg)
{
  // Initialization
  char* myStringFull = malloc(10 * sizeof(char)); if (myStringFull == NULL) return EXIT_FAILURE;

  // Finalization
  strcpy(myStringFull, "ABCD");
  myStringFull = getMyString ( myStringFull, 10);

  // Display
  printf("\n%s\n\n", myStringFull);

  // Free Memory
  free(myStringFull);

  return(EXIT_SUCCESS);
}
  • Related