I am wondering if it is possible to have a function dynamically allocate some memory, as a character array, then return a pointer to that memory to the caller through one or more of the function arguments.
it may help to show the code I have been playing around with so I'll list it below.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int test_func(char *msg)
{
int i;
char *bufptr;
bufptr = (char *) calloc(100,sizeof(char));
char recvd[] = "This is a test string";
for(i=0;i<strlen(recvd);i++)
{
bufptr[i] = recvd[i];
}
msg = bufptr;
printf("%s\n%s\n",msg,bufptr);
return 0;
}
int main()
{
char *msg;
if(test_func(msg) == 0)
{
printf("%s\n",msg);
}
free(msg);
}
The code compiles and runs on my Linux box, within tes_func the printf is able to successfully print msg and bufptr but in the main function when test_func is called and I try to print the string I had hoped would point to the dynamic string created within the function it segfaults.
Let me know if there is any way I can clarify this better.
btw I know the pointer can be returned using return, but I would like to be able to return multiple pointers to dynamically allocated strings with just one function and leave the return values such as -1 -2 -3 for telling the caller at what part of the function the problem occured.
Thanks
Steven Fletcher