开发者

Malloc, free and segmentation fault

开发者 https://www.devze.com 2023-01-19 09:47 出处:网络
I don\'t understand why, in this code, the call to \"free\" cause a segmentation fault: #include <stdio.h>

I don't understand why, in this code, the call to "free" cause a segmentation fault:

#include <stdio.h>
#include <strin开发者_如何学JAVAg.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 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");


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消