-   Programming (
-   -   Freeing memory allocated in a function (

con 01-01-2006 12:04 PM

Freeing memory allocated in a function
How do I free() *str in the code below.


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

void func(char** p)
        *p = malloc(10*sizeof(char));
        *p = "Hello";

int main(void)
        char* str;
        printf("%s World!\n", str);
        return 0;

If I compile and run it I get the following error

conny@fester:~$ ./test                                                     
Hello World!
*** glibc detected *** free(): invalid pointer: 0x08048584 ***

I'm doing this on slack 10.2

freegianghu 01-01-2006 12:40 PM

The problem here:

*p = "Hello"; /* strcpy(*p, "Hello"); ?*/

con 01-01-2006 01:03 PM

Thank you!:) I've really got to cut down on the java....;)

exvor 01-01-2006 07:36 PM

to make it a bit more understandable I wouldent allocate memory in a function but rather in the main program and pass the address to a function. then freeing it in the main program would make a little more sense. the way you got it is legal but a little confusing.

con 01-02-2006 03:25 AM

The reason I was doing it like that was, I wanted to understand how the sqlite3_exec() functions works.

In the example in the docs it is used like this

rc = sqlite3_exec(db, argv[2], callback, 0, &zErrMsg);
  if( rc!=SQLITE_OK ){
    fprintf(stderr, "SQL error: %s\n", zErrMsg);

And I didnt understand how it could access the error message in zErrMsg when it wasnt returned from the function or anything.

But yes I would also do it like you said, which is alot less confusing. But then again, doing it like in the code in my first post should be very usefull.:)

All times are GMT -5. The time now is 01:00 PM.