在C程序中使用malloc()和free()而不获取(lldb)

时间:2013-03-20 00:31:06

标签: c malloc

这是我使用malloc()free()编写的第一个程序。它对我来说是正确的,当我参考我的书时,它看起来非常类似于书中的例子。但是,当我运行程序时,我收到(lldb)提示符。

我输入8表示元素数量,输入2表示初始化值。我的xcode编译器回复“(lldb)”。

有人能引导我朝着正确的方向前进吗?

#include <stdio.h>
#include <stdlib.h>
int * make_array(int elem, int val);
void show_array(const int ar[], int n);
int main(void)
{
int *pa;
int size;
int value;

printf("Enter the number of elements: ");
scanf("%d", &size);
while (size > 0) {
    printf("Enter the initialization value: ");
    scanf("%d", &value);
    pa = make_array(size, value);
    if (pa)
    {
        show_array(pa, size);
        free (pa);
    }
    printf("Enter the number of elements (<1 to quit): ");
    scanf("%d", &size);
}
printf("Done.\n");
return 0;
}

int * make_array(int elem, int val)
{
int index;
int * ptd;

ptd = (int *) malloc(elem * sizeof (int));

for (index = 0; index < elem; index++)
    ptd[index] = val;

return ptd;
}

void show_array(const int ar[], int size)
{
int i;
for (i = 0; i < size; i++)
    printf("%d",ar[i]);
}

1 个答案:

答案 0 :(得分:0)

您的程序编译并运行(可能与您预期的一样)。以下是示例输出:

Enter the number of elements: 5
Enter the initialization value: 12
1212121212
Enter the number of elements (<1 to quit): 8
Enter the initialization value: 2
22222222
Enter the number of elements (<1 to quit): 100
Enter the initialization value: 34
34343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434
Enter the number of elements (<1 to quit): -1
Done.