A few days ago I had to use C and when working with pointers I got a little surprise.
An example in C:
#include <stdio.h>
#include <stdlib.h>
void GetPointer(int* p) {
p = malloc( sizeof(int) );
if(p) {
*p = 7;
printf("IN GetPointer: %d\n",*p);
} else {
printf("MALLOC FAILED IN GetPointer\n");
}
}
void GetPointer2(int* p) {
if(p) {
*p = 8;
printf("IN GetPointer2: %d\n",*p);
} else {
printf("INVALID PTR IN GetPointer2");
}
}
int* GetPointer3(void) {
int* p = malloc(sizeof(int));
if(p) {
*p = 9;
printf("IN GetPointer3: %d\n",*p);
} else {
printf("MALLOC FAILED IN GetPointer3\n");
}
return p;
}
int main(int argc, char** argv) {
(void) argc;
(void) argv;
int* ptr = 0;
GetPointer(ptr);
if(!ptr) {
printf("NOPE\n");
} else {
printf("NOW *PTR IS: %d\n",*ptr);
free(ptr);
}
int* ptr2 = malloc(sizeof(int));
GetPointer2(ptr2);
if(ptr2) {
printf("NOW *PTR2 IS: %d\n",*ptr2);
free(ptr2);
}
int* ptr3 = GetPointer3();
if(ptr3) {
printf("NOW *PTR3 IS: %d\n",*ptr3);
free(ptr3);
}
return 0;
}
The output:
IN GetPointer: 7
NOPE
IN GetPointer2: 8
NOW *PTR2 IS: 8
IN GetPointer3: 9
NOW *PTR3 IS: 9
In this example, the first pointer will only have "value" inside the GetPointer
method. Why using malloc
inside lasts only for the lifetime of the method?
I tried this in C++ and got the same behaviour. I thought it would retain its value, but no. I found a way through, though:
void GetPointer(int*& p) {
p = new int;
if(p) {
*p = 7;
printf("IN GetPointer: %d\n",*p);
} else {
printf("MALLOC FAILED IN GetPointer\n");
}
}
In C I can't do this trick. Is there a way to do the same in C or I have to be careful and "malloc" the pointer before attempting to give it a value?