c中的动态2d char数组

时间:2016-12-06 08:00:24

标签: c++ c

我想从客户端获取用户名和密码,并检查此用户名是否已经存在,但它不起作用且发生此错误:

  

project3.exe中的0x51D20ED2(ucrtbased.dll)抛出异常:0xC0000005:
  访问冲突读取位置0xCDCDCDCD。>

我不知道为什么?

这是我的代码:

void signup(char *input, char **usernames,int *userindex,char **passwords)
{
    int check = 0;
    char *ptr1,*ptr2;
    ptr1 = (char*)malloc(strlen(input)*sizeof(char));
    ptr2 = (char*)malloc(strlen(input)*sizeof(char));
    strtok(input, " ");
    strcpy(ptr1, strtok(NULL," "));
    strcpy(ptr2, strtok(NULL," "));
    for (int i = 1; i < *(userindex); i++)
    {
        if (!(strcmp(ptr1,usernames[i])))
        {
            check = 1;
            printf("this user has already signed up\n");
            break;
        }
    }
    if (check == 0)
    {
        usernames[*(userindex)] = (char*)malloc((strlen(ptr1))* sizeof(char));
        passwords[*(userindex)] = (char*)malloc((strlen(ptr2))* sizeof(char));
        strcpy(usernames[*(userindex)], ptr1);
        strcpy(passwords[*(userindex)], ptr2);
        printf("%s\n%s\n%d\n", usernames[*(userindex)], passwords[*(userindex)], *(userindex));
        *(userindex) = *(userindex)+1;
        free(ptr1);
        free(ptr2);
    }
}


int main()
{
    int quit = 0;
    char *input, **usernames, **passwords;
    int state, length, userindex = 1;
    usernames = (char**)malloc(sizeof(char*));
    passwords = (char**)malloc(sizeof(char*));
    while (quit == 0)
    {
        int counter = 1;
        char buffer;
        input = (char*)malloc(sizeof(char));
        printf("please enter your action\n");
        do
        {
            buffer = getchar();
            input = (char*)realloc(input, counter*sizeof(char));
            input[counter - 1] = buffer;
            counter++;
        } while (buffer != '\n');
        input = (char*)realloc(input, (counter)*sizeof(char));
        input[counter - 1] = '\0';
        state = action_decider(input);
        switch (state)
        {
            case 0:
                break;
            case 1:
                break;
            case 2:
                break;
            case 3:
                break;
            case 4:
                usernames = (char**)realloc(usernames,userindex*sizeof(char*)); 
                passwords = (char**)realloc(passwords,userindex*sizeof(char*)); 
                signup(input, usernames, &(userindex), passwords);
                break;
            case 5:
                break;
            case 6:
                quit = 1;
                break;
            case 7:
                printf("you command nonsence!\n");
                break;
        }
    }
    return 0;
}

0 个答案:

没有答案