简体   繁体   中英

c dynamic array size based on fstat

I use fstat to get the file size. I want to use this size to declare an array and then change the size with another fstat and re-use the same array. Example:

fstat(file1, &fileStat);
fsize = filestat.st_size;
char filebuffer[size-of-file1];
/* do something */
fstat(file2, &fileStat);
fsize = filestat.st_size;
char filebuffer[size-of-file2];
/* do something */

Obviously i cannot re-declare the filebuffer array, i have to declare a new one. But if i want to re-use the same array with a different size how can i do it??
Thanks!!

EDIT:

filebuffer = malloc(fsize);
if(filebuffer == NULL){
    perror("malloc");
    onexit(sockd, 0, fd, 4);
}

and

tmpfilebuf = realloc(filebuffer, fsize);
if(tmpfilebuf){
    filebuffer = tmpfilebuf;
}
else{
    perror("realloc");
    free(filebuffer);
    onexit(sockd, 0, fd, 4);
}

but now i got a segfault :(

Don't use variable length arrays. Use malloc the first time and then realloc as needed.

char *filebuffer;    
filebuffer = malloc(...);

tmp = realloc(filebuffer, ...);
if (tmp)
    filebuffer = tmp;

What you are using now is an interesting and somewhat dangerous feature called "variable length arrays". That is, you declare an array with a length computed at runtime. The problem with this approach is that it uses the stack and has no means to inform you if there's insufficient space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM