c - Segmentation fault after fopen inside a function. No issues when doing fopen in main, -


i trying learn c. goal of function foo accept string, change of it's characters , see if there file name. if such file exists, print it's contents on stdout.

sounds pretty simple , should be, keep getting segmentation fault when call fopen inside foo function. guess doing bad memory, can't figure out is.

here source:

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h>  void foo(const char* fname);  int main() {     printf("hello world!\n");     foo("a.c");     return 0; }   void foo(const char* fname) {     size_t len = strlen(fname);     printf("size %i", (int)len);     char* fname_hash;     strcpy(fname_hash, fname);      int i;     //"escape" of characters     for(i =0; < len; i++){         if( fname_hash[i] == '/'              || fname_hash[i] == '.'              || fname_hash[i] == '&'             || fname_hash[i] == ' '             || fname_hash[i] == '_'){             fname_hash[i] = '_';         }     }      if( access( fname_hash, f_ok ) != -1 ) {         printf("file exists\n");         file* fp = fopen ( fname_hash , "r" );         if( !fp ) perror(fname_hash),exit(1);          fseek( fp , 0l , seek_end);         long lsize = ftell( fp );         rewind( fp );          char* buffer = calloc( 1, lsize+1 );         if( !buffer ) fclose(fp),fputs("memory alloc fails",stderr),exit(1);          if( 1!=fread( buffer , lsize, 1 , fp) )               fclose(fp),free(buffer),fputs("entire read fails",stderr),exit(1);          printf("%s", buffer);           fclose(fp);         free(buffer);     } else {         // else     } } 

this code:

char* fname_hash; strcpy(fname_hash, fname) 

is serious problem.

char* fname_hash merely makes space on stack pointer string or characters. doesn't allocate space string, , doesn't set pointer point anywhere (it have random value).

the subsequent strcpy, copies fname random location, inevitably disaster, albeit might disaster waiting happen, when implications of overwriting random bit of memory become clear later in execution of code.

you either need use malloc allocate space (and remember clear later) or need like:

char fname_hash[100]; 

instead, have think '100' number should be, , should think happens if fname longer space you've reserved.

a reasonable rule of thumb string handling in 'c' if code looks simple , merely seems doing want using basic standard library functions, wrong , full of hazards.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -