Question concerning passing data from function using pointer
Feb 19, 2009 at 11:03am UTC
Hi all!
I've got a question as how to pass data from one function to another using pointer. My example code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#include <stdlib.h>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
void test(char *data, int *len);
int main(){
char *data;
int len;
test(data,&len);
cout << "len=" <<len<< " " << data << "\r\n" ;
free(data);
return 0;
}
void test(char *data, int *len){
*len=3;
data=(char *) malloc(sizeof (char )* *len);
data[0]='a' ;
data[1]='b' ;
data[2]='\0' ;
cout << "\r\n" << data << "--ok\r\n" ;
}
Using
g++ 2.cpp -o 2 && ./2
I get the following output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
ab--ok
len=3 ������������)�����t$1��E�D�E
�D$��$���������9�uރ�
[^_]Ë$Ð�U��S��������t1��Ћ��������u���[]Ð��U��S��
*** glibc detected *** ./2: munmap_chunk(): invalid pointer: 0x08048999 ***
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6(cfree+0x1bb)[0xb7cfe61b]
./2(__gxx_personality_v0+0x301)[0x8048931]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe0)[0xb7ca5450]
./2(__gxx_personality_v0+0x31)[0x8048661]
======= Memory map: ========
....
....
....
Aborted
What's wrong here?
I even tried passing the data using new/delete instead of malloc/free.
Thanks!
Last edited on Feb 19, 2009 at 11:04am UTC
Feb 19, 2009 at 2:26pm UTC
You are passing the "data" pointer by value to test(), which means that while test() allocates memory and fills it out correctly, the pointer it created is not returned to the calling function.
You need
1 2 3 4 5 6 7 8 9 10
void test( char ** data, int * len ) {
// ...
}
int main() {
char * data;
int len;
test( &data, &len );
}
Feb 20, 2009 at 4:34am UTC
1 2 3 4 5 6 7 8 9 10
//catch it as double pointer.
void test(char **data, int *len){
*len=3;
*data=(char *) malloc(sizeof (char ) * (*len));
*(*data + 0)='a' ;
*(*data + 1)='b' ;
*(*data + 2)='\0' ;
cout << "\r\n" << *data << "--ok\r\n" ;
}
Feb 20, 2009 at 8:06am UTC
Thanks guys!!! :)
Topic archived. No new replies allowed.