问题
I have an array of bytes
aka unsigned char
called content
. I want to split my content
array into 2 new arrays in a separate function. This function should also determine the size for each of the 2 chunks and allocate memory for them. Also, I want to be able to use both the new arrays and their sizes outside of the function. My implementation is giving me segmentation fault
and I must be doing something with pointers wrong.
Main function
int main(int argc, char *argv[]) {
byte *content = NULL;
size_t size_content;
byte *param = NULL;
size_t size_param;
byte *data = NULL;
size_t size_data;
// This works fine!
size_content = load_file_to_memory(argv[1], "rb", &content);
// split content
split_content(content, ¶m, &data,
size_content, &size_param, &size_data);
// SEGMENTATION ERROR
putchar(param[0]);
return 0;
}
Split Content Function:
void split_content(byte *content, byte **param, byte **data,
size_t size_content, size_t *size_param, size_t *size_data) {
*size_param = get_number_of_param_bytes(content);
*size_data = size_content - *size_param;
*param = malloc((*size_param) * sizeof(byte));
*data = malloc ((*size_data) * sizeof(byte));
for(size_t i=0; i<*size_param; i++) {
*param[i] = content[i];
}
for(size_t i=*size_param; i<size_content; i++) {
*data[i-*size_param] = content[i];
}
}
Get number of param bytes function:
size_t get_number_of_param_bytes(byte *content) {
size_t num_whites = 0;
size_t byte_index = 0;
do {
byte b = content[byte_index];
if(isspace(b)) {
num_whites += 1;
}
byte_index += 1;
} while (num_whites < N_WS);
return byte_index;
}
Load file to memory:
size_t load_file_to_memory(const char *filename, const char *mode, byte **buffer) {
size_t size = 0;
FILE *file = fopen(filename, mode);
if (file == NULL) {
*buffer = NULL;
printf("Unable to open file! Terminating...\n");
exit(-1);
}
size = get_file_size(file);
*buffer = malloc(size * sizeof(byte));
if (fread(*buffer, sizeof(byte), size, file) != size) {
printf("Error loading file into memory! Terminating...\n");
free(*buffer);
exit(-1);
}
fclose(file);
return size;
}
It must be something with the pointers that I am doing wrong here.
回答1:
Because of precedence rules, *param[i]
means *(param[i])
, but you actually want (*param)[i]
.
Likewise, *data[i-*size_param]
means *(data[i-*size_param])
but you want (*data)[i-*size_param]
.
Add the extra brackets around *param
and *data
.
来源:https://stackoverflow.com/questions/33534660/c-function-split-array-into-chunks