Sponsored Content
Top Forums Programming dynamic allocation vs static allocation in c Post 302321328 by lucasclaus on Sunday 31st of May 2009 06:22:56 PM
Old 05-31-2009
dynamic allocation vs static allocation in c

i wrote a tiny version of tail command using a large buffer statically allocated but, in a second time, i found another version in which i use a bidimensional array dynamically allocated.
here is the first version
Code:
 /*my tiny tail, it prints the last 5 line of a file
*/
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#define MAXSIZE 5000
void flush(char* buff,int n);
int main(int argc,char*argv[]){
    int i,n,fd,count;
    char buff[MAXSIZE];
    if (argc<2){printf("no file name inserted\n"),exit(1);}
    else if(argc>2) printf("too many parameters\n"),exit(1);
    else{    
        if((fd=open(argv[1],O_RDONLY))<0) {perror("open error"),exit(1);}
        /*file opened in readonly mode*/
        lseek(fd,-1,SEEK_END);/*the offset points the char before the end of file*/
        count=0;
        i=MAXSIZE;
        flush(buff,MAXSIZE);/*clean the buffer*/
        while(count!=5){
            if((read(fd,&buff[i],sizeof(char)))<0) perror("read error"),exit(1);
            if(buff[i]=='\n') ++count;/*count increments when the program meet a new line */
            --i;
            lseek(fd,-2,SEEK_CUR);/*read puts the offset one char forward */
            }
        for(n=i;n<MAXSIZE-1;++n)
            printf("%c",buff[n]);
        printf("\n");
        close(fd);
        }
    return 0;    
}
void flush(char* buff,int n){
    int i;
    for(i=0;i<n;++i) buff[i]=0;
}

the question is:
in program like this with large buffer is better dynamic allocation or static?
thanks
(PS: sorry for my bad english Smilie)

Last edited by lucasclaus; 06-01-2009 at 04:21 AM..
 

10 More Discussions You Might Find Interesting

1. UNIX for Dummies Questions & Answers

memory allocation

I would like to know how I could allocate some more memory to a process. Please note that I am not the root user. (1 Reply)
Discussion started by: sagar
1 Replies

2. Programming

Static variables memory allocation

Hi I want to know when and where memory for static variables are allocated in a C program. If it allocates during compilation will memory be allocated for the variable "i" during compilation itself. int count(); int main(){ printf("%d", count()); return 0; } int count() { ... (8 Replies)
Discussion started by: nathanmca
8 Replies

3. UNIX for Dummies Questions & Answers

HOw to get a variable allocation

HI Gurus, I had a requirement where i want to allocate a file name into a variable and get the file name in the subj of email. Suppose i have a file File002.pdx in the folder /home/pcs/system/files/File002.pdx Iam using a variable a = `ls /home/pcs/system/files/*.pdx` Iam using *... (2 Replies)
Discussion started by: pssandeep
2 Replies

4. Programming

Dynamic memory allocation

Hi, I am trying to process line by line of a file. But I should not be allocating static allocation for reading the contents of the file. The memory should be dynamically allocated. The confusion here is how do I determine the size of each line, put it into a buffer with the memory allocated... (11 Replies)
Discussion started by: naan
11 Replies

5. Programming

array dynamic allocation

Hi, I have the following problem: i must allocate a dynamic array from a subroutine which should return such array to main function. The subroutine has already a return parameter so i thought of pass the array as I/O parameter. I tried the following program but it doesn't work (segmentation... (11 Replies)
Discussion started by: littleboyblu
11 Replies

6. Programming

global variables and dynamic allocation

Hi, is it possible in C to allocate dynamically a global variable?? (3 Replies)
Discussion started by: littleboyblu
3 Replies

7. Programming

Memory allocation in C

Hi Experts I need some help in static memory allocation in C. I have a program in which I declared 2 variables, one char array and one integer. I was little surprised to see the addresses of the variables. First: int x; char a; printf("%u %u\n', &x, a); I got the addresses displayed... (2 Replies)
Discussion started by: unx_freak
2 Replies

8. Programming

Dynamic Memory Allocation

Hello Guys I have a small confusion in the dynamic memory allocation concept. If we declare a pointer say a char pointer, we need to allocate adequate memory space. char* str = (char*)malloc(20*sizeof(char)); str = "This is a string"; But this will also work. char* str = "This... (2 Replies)
Discussion started by: tene
2 Replies

9. Solaris

Block-based allocation and Extent-based allocation in Solaris

Hi guys! Could you tell me what's this figure about? (See the attached figure below.) This is a representation of block allocation filesystem and extent allocation filesystem in Solaris. Does this mean that in a block-based allocation, data are placed in individual blocks while in... (0 Replies)
Discussion started by: arah
0 Replies

10. Programming

Memory Allocation Query

When we dynamically allocate the memory say 100 integers say int *x = new int(1000); then does entire chunk of memory gets allocated at once after the completion of the statement? I mean will the the concept of page fault come into picture over here? (3 Replies)
Discussion started by: rupeshkp728
3 Replies
GETSERVENT_R(3) 					     Linux Programmer's Manual						   GETSERVENT_R(3)

NAME
getservent_r, getservbyname_r, getservbyport_r - get service entry (reentrant) SYNOPSIS
#include <netdb.h> int getservent_r(struct servent *result_buf, char *buf, size_t buflen, struct servent **result); int getservbyname_r(const char *name, const char *proto, struct servent *result_buf, char *buf, size_t buflen, struct servent **result); int getservbyport_r(int port, const char *proto, struct servent *result_buf, char *buf, size_t buflen, struct servent **result); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): getservent_r(), getservbyname_r(), getservbyport_r(): _BSD_SOURCE || _SVID_SOURCE DESCRIPTION
The getservent_r(), getservbyname_r(), and getservbyport_r() functions are the reentrant equivalents of, respectively, getservent(3), get- servbyname(3), and getservbyport(3). They differ in the way that the servent structure is returned, and in the function calling signature and return value. This manual page describes just the differences from the nonreentrant functions. Instead of returning a pointer to a statically allocated servent structure as the function result, these functions copy the structure into the location pointed to by result_buf. The buf array is used to store the string fields pointed to by the returned servent structure. (The nonreentrant functions allocate these strings in static storage.) The size of this array is specified in buflen. If buf is too small, the call fails with the error ERANGE, and the caller must try again with a larger buffer. (A buffer of length 1024 bytes should be sufficient for most applications.) If the function call successfully obtains a service record, then *result is set pointing to result_buf; otherwise, *result is set to NULL. RETURN VALUE
On success, these functions return 0. On error, a positive error number is returned. On error, record not found (getservbyname_r(), getservbyport_r()), or end of input (getservent_r()) result is set to NULL. ERRORS
ENOENT (getservent_r()) No more records in database. ERANGE buf is too small. Try again with a larger buffer (and increased buflen). CONFORMING TO
These functions are GNU extensions. Functions with similar names exist on some other systems, though typically with different calling sig- natures. EXAMPLE
The program below uses getservbyport_r() to retrieve the service record for the port and protocol named in its first command-line argument. If a third (integer) command-line argument is supplied, it is used as the initial value for buflen; if getservbyport_r() fails with the error ERANGE, the program retries with larger buffer sizes. The following shell session shows a couple of sample runs: $ ./a.out 7 tcp 1 ERANGE! Retrying with larger buffer getservbyport_r() returned: 0 (success) (buflen=87) s_name=echo; s_proto=tcp; s_port=7; aliases= $ ./a.out 77777 tcp getservbyport_r() returned: 0 (success) (buflen=1024) Call failed/record not found Program source #define _GNU_SOURCE #include <ctype.h> #include <netdb.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #define MAX_BUF 10000 int main(int argc, char *argv[]) { int buflen, erange_cnt, port, s; struct servent result_buf; struct servent *result; char buf[MAX_BUF]; char *protop; char **p; if (argc < 3) { printf("Usage: %s port-num proto-name [buflen] ", argv[0]); exit(EXIT_FAILURE); } port = htons(atoi(argv[1])); protop = (strcmp(argv[2], "null") == 0 || strcmp(argv[2], "NULL") == 0) ? NULL : argv[2]; buflen = 1024; if (argc > 3) buflen = atoi(argv[3]); if (buflen > MAX_BUF) { printf("Exceeded buffer limit (%d) ", MAX_BUF); exit(EXIT_FAILURE); } erange_cnt = 0; do { s = getservbyport_r(port, protop, &result_buf, buf, buflen, &result); if (s == ERANGE) { if (erange_cnt == 0) printf("ERANGE! Retrying with larger buffer "); erange_cnt++; /* Increment a byte at a time so we can see exactly what size buffer was required */ buflen++; if (buflen > MAX_BUF) { printf("Exceeded buffer limit (%d) ", MAX_BUF); exit(EXIT_FAILURE); } } } while (s == ERANGE); printf("getservbyport_r() returned: %s (buflen=%d) ", (s == 0) ? "0 (success)" : (s == ENOENT) ? "ENOENT" : strerror(s), buflen); if (s != 0 || result == NULL) { printf("Call failed/record not found "); exit(EXIT_FAILURE); } printf("s_name=%s; s_proto=%s; s_port=%d; aliases=", result_buf.s_name, result_buf.s_proto, ntohs(result_buf.s_port)); for (p = result_buf.s_aliases; *p != NULL; p++) printf("%s ", *p); printf(" "); exit(EXIT_SUCCESS); } SEE ALSO
getservent(3), services(5) COLOPHON
This page is part of release 3.25 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at http://www.kernel.org/doc/man-pages/. GNU
2008-08-19 GETSERVENT_R(3)
All times are GMT -4. The time now is 05:36 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy