开发者

small c program basic.returning a pointer

I always have this doubt in mind. Please see the below program:

#include <stdio.h>
char * function1(void);
int main()
{
    char *ch;
    ch = function1();
    printf("hello");
    free(ch);
    return 0;
}

char* function1()
{
    char *temp;
    temp = (char *)malloc(sizeof(char)*10);
    return temp;
}

am i leaking the memory here? the program does not crash in ideone with some warnings:

prog.c: In开发者_C百科 function ‘main’:
prog.c:11: warning: implicit declaration of function ‘free’
prog.c:11: warning: incompatible implicit declaration of built-in function ‘free’
prog.c: In function ‘function1’:
prog.c:19: warning: implicit declaration of function ‘malloc’
prog.c:19: warning: incompatible implicit declaration of built-in function ‘malloc’

and prints hello.

I am just a beginner in C.so please help me understand what happens after the return statement in function1.does free really frees the memory allocated in funtion1?


Memory leaking

You are code isn't leaking any memory because you do free(ch); which free's memory allocated by the malloc inside the function1 function. You can check this by printing the pointer addresses, i.e.:

char* function1()
{
  char *temp;
  temp=(char *)malloc(sizeof(char)*10);
  printf("temp: %p\n", temp);
  return temp;
}

and

ch = function1();
printf("ch: %p\n", ch);

You should see that both prints (ch and temp) will print the same address. Thus, free(ch); will free the correct malloced chunk of memory.

You can use valgrind too check if your code doesn't free allocated memory.

About the warnings

Functions free, malloc are defined at stdlib.h.

Add this in your code:

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

Also, it's not such a good idea to cast malloc return value temp=(char *)malloc(...);. Have a read here.


You need to include stdlib.h to use free and malloc.

It just happens to not matter what free and malloc actually do in your code above, so it still works.


Yes, free frees the memory allocated in function 1 and gives it back to the free memory pool so that it can be reused. this is important because if you dont free memory you can reach in a situtation where your RAM is full and calls to malloc fail.

Do include stdlib.h as it contains definition for malloc.

Also, if you use free, you are not leaking memory


Suggested alternative:

#include <stdio.h>
#include <malloc.h>

char * function1(void);

int
main(int argc, char *argv[])
{
  char *ch = function1();
  if (!ch)
    printf("ERROR: Unable to allocate memory!\n");
  else
  {
    printf("Allocation successful.\n");
    free(ch);
  }
  return 0;
}

char*
function1()
{
  return (char *)malloc(10);
}

Compile:

gcc -Wall -pedantic -o x x.c (where "x.c" is the source file, and "x" the .exe)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜