I am trying to free a memory in the main which has been allocated in a sub-function. Is this possible and am i doing this in the right fashion.
The code sample is:
char* SubFunction()
{
char *ptr= NULL;
char **values;

ptr= (char *)calloc( 100, sizeof( char ) );
if(ptr== NULL)
return ("ERROR");

strcpy( ptr, values[0] );
return ptr;
}

Main()
{
char *temp= NULL;

temp = SubFunction();
free(temp);
}

Recommended Answers

All 5 Replies

Only return ptr from the function.
Only strcpy a valid string to ptr (if it is non-NULL).

Dave,
The strcpy is valid. The question is how to free the memoty allocated in the sub-function.
Thanks

>The strcpy is valid.
No, it is not.

>The question is how to free the memoty allocated in the sub-function.
The answer is to only free what is allocated. String literals are not allocated.

>The strcpy is valid.
I was unaware that indexing an uninitialized pointer and then passing the contents of it (another uninitialized pointer) to strcpy was valid. Since I trust my knowledge more than I trust your knowledge, I'm going to say that you're wrong.

>The question is how to free the memoty allocated in the sub-function.
As long as you have a pointer to the memory, you can free it:

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

char *SubFunction(void)
{
  char *ptr = calloc(100, sizeof *ptr);

  if (ptr == NULL)
    return "ERROR";
  strcpy(ptr, "This is a valid call to strcpy");

  return ptr;
}

int main(void)
{
  char *temp = SubFunction();
  puts(temp);
  free(temp);
}

As Dave says, you won't convince any legitemate system to allow:

free("ERROR");

the equivelent of which you are doing by returning a pointer to "ERROR".

It generally works to return NULL if you can't allocate memory and the calling routine can know that NULL means "it didn't work." For example,

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

char *SubFunction(void)
{
  char *ptr = calloc(100, sizeof(char*));

  if (ptr != NULL)
      strcpy(ptr, "This is a valid call to strcpy");

  return ptr;
}

int main(void)
{
  char *temp = SubFunction();
  if (temp)
  {
     puts(temp);
     free(temp);
  }
  else
    puts("SubFunction() failed.");
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.