-7
#include <stdio.h>
#include <stdlib.h>
char *namefunct(void);

int main(int argc, char *argv[])
{
    printf("Hello, %s!!!\n", namefunct());  //namefunct is not returning tmp_name

}
char *namefunct(void)
{
    char *name = malloc(sizeof(char) * 10);
    scanf("%s", name);
    char *tmp_name = name;
    free(name);
    return tmp_name;
}

OUTPUT: ferf Hello, !!! //namefunct is not returning tmp_name How can i free the memory which is allocated in the namefunct()?

  • 1
    What in the error message is unclear? – Ted Lyngmo Jun 03 '21 at 10:08
  • 2
    Don't the errors _tell_ you what is wrong with it...? `&name_buffer` is a `char**`, so what makes you think you can treat it as an `int*`, at least without telling the compiler you really want to do such a strange cast? – underscore_d Jun 03 '21 at 10:08
  • 2
    Your `nk`function doesn't return anything and yet you assigned the result to `name_buffer`. The compiler tells you this is not possible. – fpiette Jun 03 '21 at 10:12
  • malloc gives you a pointer. using `&` on that pointer, gives you a pointer pointer, basically an address. – Eben Jun 03 '21 at 10:13
  • 2
    Your `nk` function more or less (essentially less) want to return the address of a local variable. You'll get into trouble with that since local variable will be gone after the function returns. – fpiette Jun 03 '21 at 10:15
  • 2
    Maybe you should tell what you are trying to do. – Support Ukraine Jun 03 '21 at 10:17
  • 2
    Why do the function `nk` take `int` pointers as arguments? – Support Ukraine Jun 03 '21 at 10:23
  • at least, what do you expect to achieve with this code ? – mlwn Jun 03 '21 at 11:29
  • What's wrong with this code is that memory allocation in C is hard, and its the user's problem, and you haven't learned about it yet, so you're trying things at random, which is just about guaranteed not to work. – Steve Summit Jun 03 '21 at 13:35
  • Please don't edit the code snippet from the original .. – Sorenp Jun 03 '21 at 14:02

1 Answers1

0

Ok, you dynamically allocate 10 bytes. Then you make the "name" variable (a char pointer) point to that dynamically allocated block. Then you make a char pointer which points to the same dynamically allocated block that "name" points to. Then you "free(name)" which deallocates the block that "tmp_name" also points to. "name" and "tmp_name" both point to deallocated memory that may have been taken over by another program, essentially returning a pointer pointing to trash value. I recommend this:

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

char* namefunct(void);

int main(int argc, char* argv[])
{
    char* my_name = namefunct();
    printf("Hello, %s!!!\n", my_name);  //namefunct is not returning tmp_name
    free(my_name);

    return 0;
}
char* namefunct(void)
{
    char* name = malloc(sizeof(char) * 10);
    scanf("%s", name);
    return name;
}

or, just like @Siddhant posted, you could make name a global variable and free it after

Boy boy
  • 68
  • 1
  • 6