c programming malloc question
Posted
by
user535256
on Stack Overflow
See other posts from Stack Overflow
or by user535256
Published on 2011-01-07T12:38:28Z
Indexed on
2011/01/07
14:53 UTC
Read the original article
Hit count: 227
Hello guys,
Just got query regarding c malloc() function. I am read()ing x number of bytes from a file to get lenght of filename, like ' read(file, &namelen, sizeof(unsigned char)); ' .
The variable namelen is a type unsigned char and was written into file as that type (1 byte). Now namelen has the lenght of filename ie namelen=8 if file name was 'data.txt', plus extra /0 at end, that working fine.
Now I have a structure recording file info, ie filename, filelenght, content size etc.
struct fileinfo
{
char *name;
...... other variable like size etc
};
struct fileinfo *files;
Question: I want to make that files.name variable the size of namelen ie 8 so I can successfully write the filename into it, like ' files[i].name = malloc(namelen) '
However, I dont want it to be malloc(sizeof(namelen)) as that would make it file.name[1] as the size of its type unsigned char. I want it to be the value thats stored inside variable &namelen ie 8 so file.name[8] so data.txt can be read() from file as 8 bytes and written straight into file.name[8?
Is there a way to do this my current code is this and returns 4 not 8
files[i].name = malloc(namelen);
//strlen(files[i].name) - returns 4
//perhaps something like
malloc(sizeof(&namelen)) but does not work
Thanks for any suggestions
Have tried suggested suggestions guys, but I now get a segmentation fault error using:
printf("\nsizeofnamelen=%x\n",namelen); //gives 8 for data.txt
files[i].name = malloc(namelen + 1);
read(file, &files[i].name, namelen);
int len=strlen(files[i].name); printf("\nnamelen=%d",len);
printf("\nname=%s\n",files[i].name);
When I try to open() file with that files[i].name variable it wont open so the data does not appear to be getting written inside the read() &files[i].name and strlen() causes segemntation error as well as trying to print the filename
© Stack Overflow or respective owner