所以基本上,这就是产生我的代码segmentation fault
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CORRUPT_KEY_FILE "s64581-source-key-corrupt.bin" /* ContainsKey and IV */
#define DEBUG 1
/**
* Reads content of a given file and writes it into a buffer
*
* @param filename Path of the file to be read
* @param buffer Pointer to the buffer to write into
* @param length Variable to store the filelength into
*
* @return EXIT_FAILURE if an error occurred opening th File, otherwise EXIT_SUCCESS
*/
int readFiletoBuffer(const char* filename, unsigned char* buffer, int* length) {
int i;
if(DEBUG) printf("\n\nFunction readFileToBuffer(..) called\n");
FILE *file = fopen(filename, "rb");
if(!file) {
printf("Error opening file %s", filename);
return EXIT_FAILURE;
}
fseek(file, 0 , SEEK_END);
*length = ftell(file);
rewind(file);
if(DEBUG) printf("\tLength of File %s: %d\n",filename ,*length);
buffer = (unsigned char*) malloc(*length+1);
fread(buffer, *length, 1, file);
fclose(file);
for(i=0; i<*length; i++) printf("%d:\t%X\n",14, buffer[14]);
return EXIT_SUCCESS;
}
int main(int argc, char **argv)
{
unsigned char *tmp_char;
int tmp_length, i;
tmp_char=NULL;
readFiletoBuffer(CORRUPT_KEY_FILE, tmp_char, &tmp_length);
for(i=0; i<tmp_length; i++) printf("%d:\t%X\n",i, tmp_char[i]);
return 0;
}
注意打印缓冲区内容的两个 for 循环。函数内部的那个工作正常,main
-function 中的那个产生一个segmentations fault
. 为什么会这样,在函数内分配所需内存时如何解决这个问题readFiletoBuffer
?
任何帮助表示赞赏!:D