I'm newbie with pointer in c. I'm just testing code like this
void test(uint32_t *data)
{
unsigned char raw_data[] = "this is a test data";
unsigned char *raw = (unsigned char*)malloc(strlen((char*)raw_data));
memcpy(raw, raw_data, strlen((char*)raw_data)+1);
*data = (uint32_t)raw;
}
int _tmain(int argc, _TCHAR* argv[])
{
uint32_t data;
test(&data);
printf("%s\n", data);
if (data != NULL)
{
free(data);
}
return 0;
}
I use a uint32_t
to store a unsigned char*
, when I try to free data
, I meet a error error C2664: “void free(void *)”: uint32_t can not convert to “void *"
.
How can I free data
?
First, thanks to Phạm Anh Tuấn, Gerhardh, KBlr and son on. You are very kind.
Solution:
void test(uintptr_t *data)
{
unsigned char raw_data[] = "this is a test data";
unsigned char *raw = (unsigned char*)malloc(strlen((char*)raw_data) + 1);
memcpy(raw, raw_data, strlen((char*)raw_data));
raw[strlen((char *)raw_data)] = '\0';
*data = (uintptr_t)raw;
}
int _tmain(int argc, _TCHAR* argv[])
{
uintptr_t data;
test(&data);
printf("%s\n", data);
if (data != NULL)
{
free((void *)data);
}
getchar();
return 0;
}
Must add a '\\0'
to raw
as terminating string, then free
works. And for working on 64bit
, change uint32_t
to intptr_t
.
Your program will not work on 64bit
machine since size of pointer on 64bit
machine is 8bytes
.
You can use uintptr_t
instead uint32_t
to hold the address. While freeing cast the uintptr_t
to void*
as below sample code shows.
#include<stdint.h>
#include<stdlib.h>
#include<stdio.h>
void test(uintptr_t *data)
{
unsigned char raw_data[] = "this is a test data";
unsigned char *raw = (unsigned char*)malloc(strlen((char*)raw_data));
memcpy(raw, raw_data, strlen((char*)raw_data)+1);
*data = (uintptr_t)raw;
}
int main(int argc, char* argv[])
{
uintptr_t data;
test(&data);
printf("%s\n", (char *)data);
if ((void *)data != NULL)
{
free((void *)data);
}
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.