Allocating memory using calloc and freeing

gcc 4.4.4 c89

I have a program that I am testing. I create a struct object called devname and allocate memory so that I can populate the elements. I show them and then free the allocated memory.

However, I get the following error:

invalid operands to binary != (have ‘struct Devices_names’ andvoid *’)

This is in a for for loop to display structure elements. However, I feel like testing a NULL pointer.

One more question, is there a problem with free?

Thanks so much for any advice,

#include <stdio.h>
#include <stdlib.h>

static struct Devices_names {
#define MAX_NAME_LEN 80
    int id;
    char name[MAX_NAME_LEN];
} *devname;

static void g_create_device_names(size_t devices);
static void g_get_device_names();
static void destroy_devices();

int main(void)
{
#define DEVICES 5
    g_create_device_names(DEVICES);

    g_get_device_names();

    destroy_devices();

    return 0;
}

static void g_create_device_names(size_t devices)
{
    size_t i = 0;
    devname = calloc(devices, sizeof *devname);
    if(devname == NULL) {
        exit(0);
    }

    for(i = 0; i < devices; i++) {
        devname[i].id = i;
        sprintf(devname[i].name, "device: %d", i);
    }
}

static void g_get_device_names()
{
    size_t i = 0;

    for(i = 0; devname[i] != NULL; i++) { <-- ERROR HERE
        printf("Device id --- [ %d ]\n", devname[i].id);
        printf("Device name - [ %s ]\n", devname[i].name);
    }
}

static void destroy_devices()
{
    while(devname != NULL) {
        free(devname++);
    }
}
+3
source share
4 answers

devname, NULL, . devname, struct Devices_names, , NULL - . , :

for (i = 0; i < devname_count; i++) {
    printf("Device id --- [ %d ]\n", devname[i].id);
    printf("Device name - [ %s ]\n", devname[i].name);
}

...

free(devname);
devname = NULL;
devname_count = 0;
+4

devname[i] a struct Devices_names, .

+2

:

for(i = 0; devname[i] != NULL; i++) { <-- ERROR HERE

NULL Device_names, . , Device_names.

, Device_names, .

+1

calloc , ( calloc ).

calloc , , , devname[i] != NULL, devname+i != NULL , . RTL. *alloc ( , C99). .

Also remember that an array (or any other piece of memory) allocated by a single calloc()must be freed by a single call free()with a SAME pointer, as malloc returned. Passing any other pointer to free()causes an undefined behaviaour (which is often FAIL).

So your code should be:

static struct Devices_names {
#define MAX_NAME_LEN 80
    int id;
    char name[MAX_NAME_LEN];
} *devname;
size_t devicecount;

...

    devname = calloc(devices, sizeof *devname);
    if(devname == NULL) {
        exit(0);
    }
    devicecount = devices;

...

    for(i = 0; i<devicecount; i++) { // <-- no error more here

...

static void destroy_devices()
{
    free(devname);
}
+1
source

Source: https://habr.com/ru/post/1777612/


All Articles