SIGSEGV,分段错误

时间:2014-11-24 17:35:01

标签: c++ arrays pointers function-pointers dynamic-programming

我是C ++的新手(从我的代码中可以看出)我正在使用指针和数组以及我的结构练习动态内存分配。我的代码工作正常,直到它访问" growArray"函数,然后它给我SIGSEGV错误。我无法弄清楚为什么,因为据我所知,我正确地将指针传递给指针,并且我还为新指针分配空间。是我的结构的问题,还是传递指针的问题,还是接收指针的问题?我希望这个问题有道理。

#include <iostream>
#include <string>

using namespace std;

struct FriendInfo
{
  string name;
  string address;
  string number;
};

FriendInfo *growArray(FriendInfo *p_entry, int *size);

int main()
{
    int curNum = 0;
    int size = 2;
    int userAnswer;
    FriendInfo *p_friends = new FriendInfo[size];

    cout << "Enter a friend's info?(1 for yes, 0 for no)\n";
    cin  >> userAnswer;
    while (userAnswer != 0)
    {
        if (curNum == size)
        {
            p_friends = growArray (p_friends, &size);
        }
        cout << "What is your friend's name?\n";
        cin  >> p_friends[curNum].name;
        cout << "What is your friend's address?\n";
        cin  >> p_friends[curNum].address;
        cout << "What is your friend's number?\n";
        cin  >> p_friends[curNum].number;
        curNum++;
        cout << "Enter another friend? (1 for yes, 0 for no)\n";
        cin  >> userAnswer;
    }
}

FriendInfo *growArray(FriendInfo *p_entry, int *size)
{
    *size *= 2;
    FriendInfo *p_new_friends = new FriendInfo[*size];
    for (int i = 0; i < *size; ++i)
    {
        p_new_friends[i] = p_entry[i];
    }
    delete [] p_entry;
    return p_new_friends;
}

2 个答案:

答案 0 :(得分:3)

您的问题是,即使size属于p_entrysize的价值也会增加一倍。将代码更新为:

FriendInfo *growArray(FriendInfo *p_entry, int *size)
{
    int newSize = *size * 2;
    FriendInfo *p_new_friends = new FriendInfo[newSize];
    for (int i = 0; i < *size; ++i)
    {
        p_new_friends[i] = p_entry[i];
    }
    delete [] p_entry;
    *size = newSize;
    return p_new_friends;
}

答案 1 :(得分:0)

在你的for循环中,你想在达到p_entry的大小后停止,而不是大小

FriendInfo *growArray(FriendInfo *p_entry, int *size)
{
    int orig_size = *size;
    *size *= 2;
    FriendInfo *p_new_friends = new FriendInfo[*size];
    for (int i = 0; i < orig_size; ++i)
    {
        p_new_friends[i] = p_entry[i];
    }
    delete [] p_entry;
    return p_new_friends;
}