自由();和malloc();不断崩溃(C)

时间:2018-03-06 12:42:58

标签: c string malloc free

我构建了这个代码来练习指针,程序一直在崩溃。当我向counter输入一个大数字时,它似乎崩溃了。 1-5并没有明显影响它,但当你输入30时它会不断崩溃,有时候会在分配本身malloc(...上,有时候在free(names[i]);函数中。

这里的问题是什么?

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>


int main() {
    char **names;
    char buffer[100];
    int i, bufferLen, counter;

    printf("how many names? ");
    scanf_s("%d", &counter);
    if (counter < 0) {
        printf("wrong choice\n");
        return 1;
    }

    names = (char**)malloc(77 * sizeof(char));
    if (names == NULL) {
        printf("failed...\n");
        return 1;
    }

    for (i = 0; i < counter; i++) { 
        printf("write the name!! (up to 100 chars): \n");
        gets_s(buffer, sizeof(char) * 100);
        bufferLen = strlen(buffer) + 1;
        names[i] = (char*)malloc(sizeof(char)*bufferLen);
        if (names[i] == NULL) {
            printf("failed...\n");
            return 1;
        }
        strcpy_s(names[i], sizeof(char)*bufferLen, buffer);
    }

    for (i = counter-1; i >= 0; i--) { //print names
        printf("no. %d, ptr no. %d (size: %d bytes): \n", i+1, (int)(names[i]), sizeof(names[i]));
        puts(names[i]);
    }
    for (i = 0; i < counter; i++) { 
        if (names[i] != NULL)
            free(names[i]);
    }
    if (names != NULL)
        free(names);
    return 0;
}

2 个答案:

答案 0 :(得分:4)

此:

names = (char**)malloc(77 * sizeof(char));

错误,sizeof (char)为1,这不是您想要的。

应该是:

names = malloc(77 * sizeof *names);

这与77 * sizeof (char *)相同,因为nameschar ***names的类型为char *

演员没有必要,我认为应该省略。

当然,使用文字77代替count非常奇怪(以及明显的代码气味)。

答案 1 :(得分:2)

您可能想要names = (char**)malloc(counter * sizeof(char*));

此外free处理空指针,在调用之前无需检查指针是否为空。

相关问题