Sponsored Content
Top Forums Programming Malloc problem with fread() to read file to structure in C Post 302887737 by Corona688 on Monday 10th of February 2014 01:31:29 PM
Old 02-10-2014
Consider this text:

Code:
string1
string2
42

Code:
struct mystructure {
        char *string1;
        char *string2;
        int value;
} mystr;

fread(&mystr, sizeof(mystr), 1, fp);

printf("%s\n", mystr.string1);
printf("%s\n", mystr.string2);
printf("%d\n", mystr.value);

What, exactly, does this print?

Code:
Segmentation fault

Why...? Because 'char *string1' is a pointer: A four-byte(on my system, 8-byte on yours) integer that describes a location in memory. The four bytes 'stri' aren't likely to refer to any valid memory, and even if we win the lottery and find a valid location, it probably won't be pointing to a location containing "string1\n".

So we do this:

Code:
struct mystructure {
        char string1[64];
        char string2[64];
        int value;
} mystr;

fread(&mystr, sizeof(mystr), 1, fp);

printf("string1:  %s\n", mystr.string1);
printf("string2:  %s\n", mystr.string2);
printf("value:  %d\n", mystr.value);

What does it print now?

Code:
string1:  string1
string2
42
¿Ó¿om·Ó¿àè|·
string2:
value:  -1216741388

Oh, it stuffed it all into 'string1' because it didn't stop when the string did.

C library calls will not give your structures the special treatment to put anything but the file's literal contents in that memory? How would it? It doesn't know what your structure is:

Code:
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

It only knows it was told, 'put this many bytes at this memory', and it did.

C does not know your data structures. Only your own functions do, and then, only if you tell them what it is, and it's still up to you to use them -- it does what you tell it, nothing more. If you want things read in any way other than a raw block, you have to write that.

Code:
#include <stdio.h>
#include <string.h>

struct mystruct {
 char *string1;
 char *string2;
 int value;
};

struct mystruct *readmystruct(struct mystruct *s, FILE *fp)
{
 char buf[4096];
 if(fgets(buf, 4096, fp) == NULL) return(NULL);
 s->string1=strdup(buf);
 if(fgets(buf, 4096, fp) == NULL)
 {
   free(s->string1);
   return(NULL);
 }
 s->string2=strdup(buf);
 if(fgets(buf, 4096, fp) == NULL)
 {
  free(s->string1);
  free(s->string2);
  return(NULL);
 }
 s->value=atoi(buf);
 return(s);
}

int main()
{
 struct mystruct s;
 if(readmystruct(&s, stdin) == NULL)
 {
        printf("Couldn't read struct\n");
        return(1);
 }

 printf("string1:  %s\n", s.string1);
 printf("string2:  %s\n", s.string2);
 printf("value:  %d\n", s.value);

 return(0);
}

Code:
$ ./a.out < lines
string1:  string1

string2:  string2

value:  42

$

"C library calls do not know your data structures" is a ready answer to a lot of questions. Like, "will free() deallocate pointers inside a structure pointer I give it, or just the structure itself?" It does not, indeed cannot -- it would need to know what's inside it, and it doesn't. All it has is the 4/8 bytes of the pointer you passed into it, and a list(well, heap) of what pointers it gave you before.

Last edited by Corona688; 02-10-2014 at 02:40 PM..
This User Gave Thanks to Corona688 For This Post:
 

10 More Discussions You Might Find Interesting

1. Programming

a problem about malloc()

1 . Thanks everyone who read the post. 2 . the programe is that : #include <stdio.h> #include <string.h> void do_it(char *p) { p = (char *) malloc(100); (void )strcpy(p,"1234"); } int main(void) { char *p; do_it(p); (void )printf("p = %s \n",p); (1 Reply)
Discussion started by: chenhao_no1
1 Replies

2. UNIX for Dummies Questions & Answers

Problem w. case structure

Hello, I am having a problem setting a range of numbers for the "case" structure. I can use with no problems, but when I use it doesn't work??? Does the case struture allow numeric ranges? eg: echo -e "enter number between 0 and 60: \c" read $answer case $answer in ) echo... (2 Replies)
Discussion started by: Joe54321
2 Replies

3. Programming

How to read task_struct process structure of Linux

Hi, I want to read the task_struct structure in Linux in order to get the names & pids of all processes. How can this be done?? Thanks in adv, molu (4 Replies)
Discussion started by: molu
4 Replies

4. Shell Programming and Scripting

File read & execute problem

Hi folks, Need your help. I am writing a KSH script to read a few commands from a file & execute. I am using the following code to read the file line by line & excute each command. When I am printing each line I see it is printing properly but while excuting, the particular "ps" command... (5 Replies)
Discussion started by: tipsy
5 Replies

5. Programming

problem in reading file using fread

Hi All, These are the two ways i tried to read file but i getting work with second one not with the first. char buf; // Defining space for buf ctrlfnum = fopen(filename_arr.control_fname,"r"); 1) n = fread(buf,sizeof(buf),1,ctrlfnum); ============== (not works) 2) n =... (4 Replies)
Discussion started by: arunkumar_mca
4 Replies

6. Shell Programming and Scripting

problem with listing of directory structure

Hi When im listing (ls -al ) its listing directories without / at the end of directories dir1 dir2 dir3 and i need to list directories with dir1/ dir2/ dir3/ and this should not be made by command ls -F / should be embedded at the last since one of the scripts reads directories... (1 Reply)
Discussion started by: vasanthan
1 Replies

7. Programming

Problem in static structure array in C

Hi, I have a following problem in C. I have a function A in which I used to call another function (function B) and pass an array of values through array variable by using below:- foo=functionB(array); In functionB, i used to just return some "values" (e.g return num;) in order to pass... (1 Reply)
Discussion started by: ahjiefreak
1 Replies

8. SCO

Read error on bootinfo structure at 0x800

hi One of our SCO 5.0.6 server is crashing every second or third time during rebooting with kernel panic. According to this SCO manual: http://wdb1.sco.com/kb/showta?taid=106181&qid=1689366546&sid=504668569&pgnum=1 I've saved dump image into a floppy and I've done the following steps: #... (0 Replies)
Discussion started by: ccc
0 Replies

9. UNIX for Dummies Questions & Answers

Malloc and File Creation

How can I use malloc with copying/creating files? Is this the correct way? I'm a bit confused... int in_fd; int *out_fd; char buffer; in_fd = open(av, O_RDONLY); out_fd = malloc(strlen(av)+strlen(av)+2); sprintf"(buffer,%s/%s", av,av); (5 Replies)
Discussion started by: l flipboi l
5 Replies

10. Solaris

Structure of USCSICMD and CDB for USCSI Read/Write

I am using Solaris 10u11 on x86 machine, i am root, i want to use a gcc compiled code to use read10/write10 function of USCSI solaris library to access data from a normal USB mass storage device. I am able to open a device prior to sending USCSI command via IOCTL. IOCTL command works ok as... (0 Replies)
Discussion started by: danish2012
0 Replies
All times are GMT -4. The time now is 12:23 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy