Solved

Dynamic programmig, string and malloc

Posted on 2006-11-24
12
317 Views
Last Modified: 2012-05-05
char name[20];

file *smth;
smth=fopen("asd.txt","r");
....
fscanf(smth, "%s", name);
...
..

printf ( " name is : %s", name );


i want to learn how to create dynamic programming for name array ? i want to "fscanf" the string from txt and i am going to use it.. but for ex i dont know its length i want to use malloc..
0
Comment
Question by:thefirstfbli
  • 4
  • 2
  • 2
  • +2
12 Comments
 
LVL 24

Accepted Solution

by:
fridom earned 250 total points
ID: 18010550
Well at first fscanf with %s and no limit is asking for trouble. What happens if name is longer then 20 chars? A buffer overflow and that means an vulnerable program.

The usual way to try you undertaking is having a very buffer and fgets into it. If you do want to allocate this space you'd do it as follows

- Either read from the start of the line till the end of line and count the chars than seek back, allocate the proper space
and run fread with the found limit (however I've never seen that applied in the "wild"
- so do the following:
allocate some buffer

char * buf = malloc(100);

Then read the line char by char

do {
    c = getchar();
    if (c == EOF) {
           break;
    }
    if (c == '\n') {
0
 
LVL 24

Expert Comment

by:fridom
ID: 18010562
Well at first fscanf with %s and no limit is asking for trouble. What happens if name is longer then 20 chars? A buffer overflow and that means an vulnerable program.

The usual way to try you undertaking is having a very buffer and fgets into it. If you do want to allocate this space you'd do it as follows

- Either read from the start of the line till the end of line and count the chars than seek back, allocate the proper space
and run fread with the found limit (however I've never seen that applied in the "wild"
- so do the following:
allocate some buffer
int some_size = 100;
char * buf = malloc(some_size);
char *pc = NULL;

Then read the line char by char
int i = 0;
do {
    c = getchar();
    if (c == EOF || c == '\n') {
           break;
    }
    if (! (i < some_size-1) ) { // - 1 for the trailing '\0'
        /* buffer to small reallocate it I propose usine *2 as new size */
     some_size *= 2;
      pc = realloc(buf, some_size);
      if (! pc ) {
          /* error handling */
          break;
      } else {
         /* can use buffer safely */
       buf = pc;
      }
     buf[i]  = c;
     }
   ++i;
} while (true);

buf[i] = '\0';

That's the idea (minus typos etc.)

Regards
Friedrich
0
 
LVL 1

Author Comment

by:thefirstfbli
ID: 18010900
thanks,

char * buf = malloc(some_size);

what about malloc ? still we say some_size ? what is the idea behind of malloc, if it is largen than some_size ?
0
 
LVL 1

Author Comment

by:thefirstfbli
ID: 18011108
and also cant i use array to pointer, name -->array then array --->pointer than malloc pointer ?

i want to use it like this.
0
 
LVL 6

Expert Comment

by:_iskywalker_
ID: 18011898
malloc reserves somesize*8bits of memory, it is very dangerous changing pointers with malloc, since only char has 8 bits short have 16 bits and int have (mostly) 32 bits, this is very platform dependent. So be careful using malloc around, if you dont want to get seg faults.
you can always use:
char * buf = malloc(some_size*sizeof(char));
which can help you in much places.
about your arraws:
void *p0;
int p1[10];
int *p2;
int *p3;
int i=0;

p0=(void *)p1;
p2=malloc(sizeof(int)*10);
p3=p0
for(;i<10;i++){
p2[i]=p3[i];
//or
p2[i]=p1[i];
}

0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 2

Expert Comment

by:Razor2k5
ID: 18015107
Hi,

use:

#include      <sys/types.h>
size_t      read(int fildes,void *buf,size_t nbyte);

As an example of reading each char:

...
buff=malloc(1*sizeof(char));
...
/*read until EOF*/
while(read(smth,(char *)buff,1)){
/*do something*/
}
...
0
 
LVL 24

Expert Comment

by:fridom
ID: 18017558
this posting about malloc is nonsense. malloc has no idea about some memory * 8 bit of size. and
sizeof(char) == 1 (that's guaranteed in the standard), well by chance it happens that char usually has 8 bits. but that does not matter really.

Of course you have to provide some initial size for malloc that's a starting point and you can resize this size with realloc that it what my code shows. this read stuff is at least a bit problematic. It is used properly here but it's surely not any valid "string", because there's just room for 1 byte in the allocated space and I doubt it makes very much sense to just work on the input char-by-char if that is intended it seems to be a waste to use read (which BTW is non portable) and use fgetc instead.

Friedrich
0
 
LVL 2

Expert Comment

by:Razor2k5
ID: 18017596
0
 
LVL 8

Assisted Solution

by:jk2001
jk2001 earned 250 total points
ID: 18018316
What about fgets?  That lets you specify the buffer size, so you don't overflow.  If you fill up the buffer, try to reallocate more space, and then call fgets again.
0
 
LVL 24

Expert Comment

by:fridom
ID: 18020131
what jk2001 tells is an alternative. Howerver you have to keep in mind that you have
either keep the read in string somewhere
or that you reset the read position while rereading.

Regards
Friedrich
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now