c - Malloc, free and segmentation fault -
i don't understand why, in code, call "free" cause segmentation fault:
#include <stdio.h> #include <string.h> #include <stdlib.h> char *char_arr_allocator(int length); int main(int argc, char* argv[0]){ char* stringa = null; stringa = char_arr_allocator(100); printf("stringa address: %p\n", stringa); // same address "arr" printf("stringa: %s\n",stringa); //free(stringa); return 0; } char *char_arr_allocator(int length) { char *arr; arr = malloc(length*sizeof(char)); arr = "xxxxxxx"; printf("arr address: %p\n", arr); // same address "stringa" return arr; } can explain me?
thanks, segolas
you allocating memory using malloc correctly:
arr = malloc(length*sizeof(char)); then this:
arr = "xxxxxxx"; this cause arr point address of string literal "xxxxxxx", leaking malloced memory. , calling free on address of string literal leads undefined behavior.
if want copy string allocated memory use strcpy as:
strcpy(arr,"xxxxxxx");
Comments
Post a Comment