Solved

Dynamic programmig, string and malloc

Posted on 2006-11-24
12
320 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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
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
 
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

ScreenConnect 6.0 Free Trial

Explore all the enhancements in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

778 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