mu_sa
mu_sa

Reputation: 2735

Same file, same filesize but the memory comparision returns non zero

#define "/local/home/..."

FILE *fp;

short *originalUnPacked;
short *unPacked;

int fileSize;

fp = fopen(FILENAME, "r");
fseek (fp , 0 , SEEK_END);
fileSize = ftell (fp);
rewind (fp);

originalUnPacked = (short*) malloc (sizeof(char)*fileSize);
unPacked = (short*) malloc (sizeof(char)*fileSize);

fread(unPacked, 1, fileSize, fp);
fread(originalUnPacked, 1, fileSize, fp);    

if( memcmp( unPacked, originalUnPacked, fileSize) == 0) 
{
 print (" unpacked and original unpacked equal ") // Not happens
}

My little knowldege of C says that the print statement in the last if block should be printed but it doesnt, any ideas Why ??

Just to add more clarity and show you the complete code i have added a define statement and two fread statement before the if block.

Upvotes: 0

Views: 92

Answers (2)

another.anon.coward
another.anon.coward

Reputation: 11405

Few points for your consideration:
1. The return type of ftell long int so it is better to declare fileSize as long int (as sizeof(int) <= sizeof(long)).
2. It is a better practice in C not to typecast the return value of malloc. Also you can probably get rid of sizeof(char) when using in malloc.
3. fread advances the file stream thus after the first fread call the file stream pointer has advanced by the size of the file as dictated by fileSize. Thus the second fread immediately after that will fail to read anything (assuming the first one succeeded). This is the reason why you are seeing the behavior mentioned in your program. You need to reset the file stream pointer using rewind before the second call to fread. Also you can check the return value of fread which is the number of bytes successfully read to check how many bytes were actually read successfully. Try something on these lines:

size_t bytes_read;
bytes_read = fread(unPacked, 1, fileSize, fp);
/* some check or print of bytes read successfully if needed */
/* Reset fp if fread was successfully to load file in memory pointed by originalUnPacked */
rewind(fp);
bytes_read = fread(originalUnPacked, 1, fileSize, fp);
/* some check or print of bytes read successfully if needed */
/* memcmp etc */

4. It may be a good idea to check for the return values of fopen, malloc etc against failure i.e. NULL check in case of fopen & malloc.
Hope this helps!

Upvotes: 3

Jon
Jon

Reputation: 437904

The memory allocated with malloc is not pre-initialized, so its contents are random and thus almost certainly different for the two allocations.

The expected (probabilistically speaking, "certain") result is exactly what happens.

Did you mean to load the file into both of these buffers before testing with memcmp but forgot to do so?

Upvotes: 1

Related Questions