简体   繁体   中英

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM