Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Malloc, free and segmentation fault

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

like image 622
Segolas Avatar asked Oct 08 '10 10:10

Segolas


2 Answers

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");
like image 137
codaddict Avatar answered Nov 08 '22 10:11

codaddict


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.

like image 27
Ignacio Vazquez-Abrams Avatar answered Nov 08 '22 11:11

Ignacio Vazquez-Abrams