views:

111

answers:

4

Hi,

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

+2  A: 

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.

Ignacio Vazquez-Abrams
+1  A: 

When you write a constant string in C, such as "xxxxxx", what happens is that that string goes directly into the executable. When you refer to it in your source, it gets replaced with a pointer to that memory. So you can read the line

 arr = "xxxxxxx";

Treating arr as a number as something like:

 arr = 12345678;

Where that number is an address. malloc has returned a different address, and you threw that away when you assigned a new address to arr. You are getting a segfault because you are trying to free a constant string which is directly in your executable -- you never allocated it.

luqui
A: 

You are setting arr to the return value of malloc(), which is correct. But you are then reassigning it to point at the string constant "xxxxxxx". So when you call free(), you're asking the runtime to free a string constant, which causes the seg fault.

Oli Charlesworth
+10  A: 

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 malloced 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");
codaddict
You are right on the UB part: Calling `free` with any pointer value (other than `NULL`) not from `malloc` or `realloc` gives undefined behaviour.
schot