使用 free() 时出现分段错误

2024-01-01

此代码会导致分段错误:

int main(){

    char *p;
    char a[50] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    p = (char *)malloc(50*sizeof(char));

    if(!p){
            cout << "Allocation Failure";
            cout << "\n";
    }
    else{
            cout << "Allocation Success";
            cout << "\n";
            p = a;
            cout << p;
            cout << "\n";
            free(p);
    }

    return 0;
}

执行该程序后的输出为:

Allocation Success

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

Segmentation fault

我无法找到该错误。可能是什么原因?


This:

p = a;

copies the pointer, not the contents of the pointed-to memory. p now points at the first element of the array a. So when you do free(p), you're trying to free a non-dynamic array, which doesn't make any sense.1

你应该调查一下strncpy() http://en.cppreference.com/w/cpp/string/byte/strncpy复制字符串。


1. And it also causes a memory leak.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 free() 时出现分段错误 的相关文章

随机推荐