C语言 调整动态分配数组的大小



我已经编写了以下代码来调整数组的大小,如果一个项目将超出存储它的范围。这段代码按预期工作。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//! Our location struct for storing locations
struct location
{
    char loc_name[35];
    char description[85];
    float latitude;
    float longitude;
};
void runMenu();
void add_location(struct location** p_location_array, int* p_array_size, int* p_current_size);
void resize_array(struct location** p_location_array, int* p_array_size);
void print (struct location* p_array, int p_current_size);
// Print out the main menu to the user.
void runMenu()
{
    printf("[A]dd additional Locationsn");
    printf("[P]rint the current list of locationsn");
    printf("[Q]uit the programn");
}
//! Resize the array to two times it's origional size.
void resize_array(struct location** p_location_array, int* p_array_size)
{
    // Allocate enough space for two times the size of the array
    int new_size = 2 * (*p_array_size);
    struct location* new_location_array = malloc(new_size * sizeof(struct location));
    if (!new_location_array)
    {
        printf ("Cannot add more elements heap has exhausted all spacen");
        exit(1);
    }
    // Copy the old array to the new array.
    memcpy(new_location_array, *p_location_array, ((*p_array_size ) * sizeof(struct location)));
    // We will update the current size of the array for later checking.
    *p_array_size = 2 * (*p_array_size);
    // We have a copy of the old array so we can free it.
    free(*p_location_array);
    // The contents of the pointer reference get the array we malloced in this function
    *p_location_array = new_location_array;
}
//! Add a new location to our array. If the array isn't large enough resize it then insert the new struct.
void add_location(struct location** p_location_array, int* p_array_size, int* p_current_size )
{
    // Get the users input
    struct location new_location;
    printf("Enter the new location namen ");
    fscanf(stdin, "%s", new_location.loc_name); 
    printf("Enter a description of the locationn");
    fscanf(stdin, "%s", new_location.description),
    printf("Enter the latituden");
    fscanf(stdin, "%f", &new_location.latitude);
    printf("Enter the longituden");
    fscanf(stdin, "%f", &new_location.longitude);
    // Check to see if the size is correct.
    if (*p_array_size <= *p_current_size)
    {
        // If not the correct size resize the array
        resize_array(p_location_array, p_array_size);
    }
    // Insert our sruct
    (*p_location_array)[*p_current_size] = new_location;
}
//! Loop over and print out the locations
void print (struct location* p_array, int p_current_size)
{
    int i;
    for (i = 0; i < p_current_size; i++)
    {
        struct location current = p_array[i];
        printf("%s :  %s  : %f : %fn", current.loc_name, current.description, current.latitude, current.longitude);
    } 
}

int main()
{
    char choice = ' ';
    short control = 1;
    int size;
    int currentSize = 0;
    printf("Enter the inital size of the arrayn");
    scanf(" %d", &size);
    // Make a new struct array from the heap
    struct location* m_location_array = 
         malloc(size * sizeof(struct location));
    // Make sure we have a valid chunk of the heap.
    if (!m_location_array)
        exit(1);
    while(control)
    {
        runMenu();
        scanf(" %c", &choice);
        switch (choice)
        {
            case 'a':
            case 'A':
                // Do Add additional
                add_location(&m_location_array, &size, &currentSize);
                currentSize++;
                break;
            case 'p':
            case 'P':
                // Do printing
                print (m_location_array, currentSize);
                break;
            case 'Q':
            case 'q':
                control = 0;
                break;
            default:
                printf("Invalid inputn");
        }   
    }
    // clean up after ourselves.
    free (m_location_array);
    return 0;
}

然而,当我最初编写这个函数时,我认为可以只传递指向数组的指针,而不是像这样传递对指针的引用:

 void resize_array(struct location* p_location_array, int* p_array_size)

调用这个函数而不引用指针会抛出一个段错误,表明内存被双重释放。这是因为指针传递给函数以某种方式得到释放和重新分配吗?此外,为什么需要像这样通过引用传递指针?即使指针是原始指针的副本,它不会仍然指向同一块内存吗?如能指出正确的方向,我将不胜感激。

你给了一个指向函数的指针,你在那里调用了free。这样内存就被释放了。在此之后,使用该指针会导致未定义的行为,您可能不会使用它。

修改函数内部的指针变量不会改变函数外部的指针。这就是为什么你需要一个指向指针的指针,这样你就可以在函数外修改指针变量。

即使指针是原始指针的副本,它不是仍然指向同一块内存吗?

是的,这就是问题所在:除非你改变它,否则它将一直指向同一个地方。如果你做一个新的malloc,它将指向一个完全不同的地方。

还有一个提示:realloc可能值得一看。

如果将指针传递给函数,则该指针是原始指针的副本。即使你在函数内部给这个指针赋值,比如

p_location_array = new_location_array;

原始指针(在函数之外)的值仍然没有改变。所以如果原始指针指向某个内存区域然后你把它传递给函数

void resize_array(struct location *p_location_array, int* p_array_size)

和你已经调用free()内部的函数和分配NULL的指针,在你的函数已经返回原来的指针将比较为不是NULL

// warning, changed prototype
void resize_array(struct location *p_location_array, int* p_array_size);
struct location *loc = malloc(size * sizeof(struct location)); // assume loc = 0x12345678
if (loc == NULL) EXIT_FAILURE;
// change pointer inside the function
// assign NULL to the pointer
resize_array(loc, size_p);
if (loc != NULL)
    free(loc);  // this will be called, loc is still 0x12345678,
                // double free, UB

相关内容

  • 没有找到相关文章

最新更新