I don't understand why, in this code, the call to "free" cause a 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 as "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 as "stringa"
return arr;
}
Can someone explain it to me?
Thanks, Segolas
You are allocating the memory using malloc
correctly:
arr = malloc(length*sizeof(char));
then you do this:
arr = "xxxxxxx";
this will cause arr
point to the address of the string literal "xxxxxxx"
, leaking your malloc
ed memory. And also calling free
on address of string literal leads to undefined behavior.
If you want to copy the string into the allocated memory use strcpy
as:
strcpy(arr,"xxxxxxx");
The third line of char_arr_allocator()
wipes out your malloc()
result and replaces it with a chunk of static memory in the data page. Calling free()
on this blows up.
Use str[n]cpy()
to copy the string literal to the buffer instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With