malloc的,免费和分割故障 [英] Malloc, free and segmentation fault

查看:123
本文介绍了malloc的,免费和分割故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白,为什么在这个code,调用自由导致段错误:

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?

谢谢,
Segolas

Thanks, Segolas

推荐答案

您正在使用的malloc分配内存正确的:

arr = malloc(length*sizeof(char));

那么你这样做:

arr = "xxxxxxx";

这将导致改编指向字符串的地址XXXXXXX 漏水的malloc ED内存。而且还呼吁免费上未定义行为字符串线索地址。

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.

如果你想的复制的串入分配的内存使用的strcpy 为:

If you want to copy the string into the allocated memory use strcpy as:

strcpy(arr,"xxxxxxx");

这篇关于malloc的,免费和分割故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆