munmap_chunck(): invalid pointer in c -
i have program i've written data analysis, , data stored in global structure called p. allocate memory structure in 1 function , then, since need entire program, don't call free until end of main. malloc not called in main because size of array obtained file, figured made sense read in file , allocate memory there, rather doing of in main.
#include <stdlib.h> #include <stdio.h> typedef struct data { /* variables*/ } data; data *p; void function1(void); int main(int argc, char **argv) { function1(); /*do stuff*/ free(p); return 0; } void function1(void) { if(!(p = (data *)malloc(nums * sizeof(data)))) { printf("error!\n"); exit(exit_failure); } /*do stuff*/ } essentially, when run code, error: munmap_chunck(): invalid pointer. i've done bit of reading , seems related function free. i've read malloc , free should called in same function. if case, question is: since p global variable, why matter function malloc , free called in particular variable? if, in fact, problem not caused malloc , free being called in different functions, have advice on might instead? thank much!
this common problem occurs when provide free pointer doesn't point start of allocated memory block. example, code
int* = malloc(sizeof(int)); // allocate space 1 int ... free(something); will work fine providing free original pointer returned malloc. however, if this:
int* = malloc(sizeof(int) * 5); // allocate space 5 ints ... += sizeof(int); // shift allocated memory 1 int ... free(something); then free has been provided pointer somewhere in middle of allocated memory block. means essentially, free has no idea block starts or ends, therefore throwing error. can fixed storing original pointer value in pointer:
int* = malloc(sizeof(int) * 5); int* another_something = something; // `another_something` contains same pointer value `something` ... += sizeof(int); // `something` changes, `another_something` doesn't ... free(another_something); // free original pointer so, in case, this:
#include <stdlib.h> #include <stdio.h> typedef struct data { /* variables*/ } data; /* declare data*, p1 */ data *p, *p1; void function1(void); int main(int argc, char **argv) { function1(); /*do stuff*/ /* free original pointer, in p1 */ free(p1); return 0; } void function1(void) { if(!(p = (data *)malloc(nums * sizeof(data)))) { printf("error!\n"); exit(exit_failure); } /* store original value of `p` in p1 */ p1 = p; /*do stuff*/ } lastly, please fix naming conventions. p , function1 awful names.
Comments
Post a Comment