chkdrv chkdrv - 1 year ago 108
C Question

C - realloc() pointer then set value inside function

I'm trying to write a function in C that reads a file into char array passed to it.

void read_file(char* path, char** bufptr, char* buffer){
/* open the file, and exit on errors */
FILE *fp = fopen(path, "r");
if(fp == NULL){
perror("Failed to open file");
exit(1);
}
/* figure out how long the file is to allocate that memory */
fseek(fp, 0, SEEK_END);
long length = ftell(fp);
rewind(fp);
/* allocate memory */
*bufptr = realloc(*bufptr, length+1);
fread(buffer, length, 1, fp);
buffer[length] = 0;
}


The idea is that I would use it something like this:

int main(int argc, char** argv){
char* somestring = malloc(1024);
core_read_file("/some/file/path", &somestring, somestring);
printf("In main(): %s\n", somestring);
free(somestring);
return 0;
}


However whenever I use it, while the program compiles, the printf prints nothing to the console. I'm starting out and kind of understand the idea of "indirection" to a very very basic degree, but can someone explain to me why my code doesn't work the way I expect it to, and how I should go about implementing this function.

(This isn't a homework assignment so any solution or method that works is perfect)

Answer Source

The last two lines of read_file should be:

  fread(*bufptr, length, 1, fp);
  (*bufptr)[length] = 0;

The pointer in the newly allocated buffer is in *bufptr, not in buffer.

But your program is overly complicated, you don't need to pass three parameters do read_file. Two is enough, like this:

void read_file(char* path, char** bufptr) {
  /* open the file, and exit on errors */
  FILE *fp = fopen(path, "r");
  if (fp == NULL) {
    perror("Failed to open file");
    exit(1);
  }
  /* figure out how long the file is to allocate that memory */
  fseek(fp, 0, SEEK_END);
  long length = ftell(fp);
  rewind(fp);
  /* allocate memory */
  *bufptr = realloc(*bufptr, length + 1);
  fread(*bufptr, length, 1, fp);
  (*bufptr)[length] = 0;
}    

int main(int argc, char** argv) {
  char* somestring = malloc(1024);  //  char* somestring = NULL would be even better here
  read_file("readme.txt", &somestring);
  printf("In main(): %s\n", somestring);
  free(somestring);
  return 0;
}

There is still no error checking for realloc here for brevity.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download