-1

Assume following example code:

//open some file

char* data[10];

for ( int i=0; !feof(file) && i < 10; i++ )
{
    fgets( data[i], 100, file );
}

//close file

AFAIK using a pointer array without allocating memory to individual pointers like this is unsafe and if works, it's because there happens not to be any vital information contained at that memory region.

But I have seen many people using it like this and I doubted myself.

Is this a proper use?

aulven
  • 521
  • 3
  • 14

1 Answers1

1

Your code has undefined behavior and is extremely unsafe.

The elements of your data arrays are pointers, and their initial values are garbage. They could point to memory that's in use for some other purpose, or to memory that doesn't exist. I'd be surprised if your program didn't crash.

You don't need to call malloc. You could define

char data[10][100];

Furthermore, you shouldn't use feof to determine when you've finished reading input. feof returns a true value if the previous input function has failed due to running out of input. If there's an error other than running other than running out of input, ferror will return true and feof will not. Use the value returned by fgets to determine whether it succeeded.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631