logo
down
shadow

Accessing dynamically allocated structure received through socket


Accessing dynamically allocated structure received through socket

By : manish
Date : November 22 2020, 10:54 AM
To fix the issue you can do The send() function prototype is
code :
ssize_t send(int sockfd, const void *buf, size_t len, int flags);
(void)&struct1
(const void *)struct1


Share : facebook icon twitter icon
How to byte array received from socket, to C# structure

How to byte array received from socket, to C# structure


By : yoni
Date : March 29 2020, 07:55 AM
like below fixes the issue By default, Delphi's packed records align fields by single byte boundary.
Hence, you should use something like this:
code :
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct TREC_DATA
{
      public byte ID;
      [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
      public byte[] MAC_ADDRESS;
      public uint fieldCard;
      public short fieldSI;
      public ushort fieldW;
      [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
      public byte[] SERIAL_NUMBER;
      public float fieldSingle;
      [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
      public byte[] fieldArrOfB;    
} 
How to free Structure containing dynamically allocated double pointer to another structure type?

How to free Structure containing dynamically allocated double pointer to another structure type?


By : totalflux
Date : March 29 2020, 07:55 AM
around this issue Here's an adaptation of your code. I've cleaned up many points that I made in the comments to the question. In particular:
The structure names are removed from the namespace reserved for the implementation. Operations are checked and errors are reported. If the file open fails, uninitialized pointers are not freed. If the file open fails, the code doesn't try to close the unopened file stream. Because failure to allocate exits the program, there are fewer checks for nullness. The code counts how many adjacent nodes there are in a row and allocates the correct space all at once, rather than allocating the array one element at a time. I've preserved the null terminator for the adjacency list, though it isn't really necessary. By default, the program reads from a file data. You can override that by specifying the file to read on the command line.
code :
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stderr.h"

typedef struct Node
{
    int nodeNumber;
    int adjNum;
    struct Node **adjacent;
} Node;

typedef struct Graph
{
    int vc;
    char *name;
    int **AM;
    Node **node;
} Graph;

static void createGraphFromAM(Graph *graph);

static Graph *readGraphFromTxt(const char *filename)
{
    FILE *fp = fopen(filename, "r");
    if (fp == 0)
        err_syserr("failed to open file %s for reading\n", filename);
    Graph *graph = malloc(sizeof(*graph));
    if (graph == 0)
        err_syserr("failed to allocate %zu bytes\n", sizeof(*graph));
    char line[100];
    if (fgets(line, sizeof(line), fp) == 0)
        err_error("premature EOF - no graph name\n");
    line[strcspn(line, "\n")] = '\0';
    char *gname = strdup(line);
    if (fgets(line, sizeof(line), fp) == 0)
        err_error("premature EOF - no auxilliary info\n");
    int vc = -1;
    if (fscanf(fp, "%d", &vc) != 1)
        err_error("format error: didn't get an integer\n");
    if (vc < 1 || vc > 20)
        err_error("size of graph out of control: %d\n", vc);

    int **AM = (int **)malloc(sizeof(int *) * vc);
    if (AM == 0)
        err_syserr("failed to allocate %zu bytes\n", sizeof(int *) * vc);

    for (int i = 0; i < vc; i++)
    {
        AM[i] = (int *)malloc(sizeof(int) * vc);
        if (AM[i] == 0)
            err_syserr("failed to allocate %zu bytes\n", sizeof(int) * vc);
        if (fscanf(fp, "%s", line) == EOF)
            err_error("premature EOF - not enough lines of data for the adjacency matrix\n");
        if (strlen(line) < (size_t)vc)
            err_error("Adjacency matrix line is too short (got [%s] (%zu); wanted %d)\n",
                      line, strlen(line), vc);
        for (int j = 0; j < vc; j++)
        {
            assert(line[j] == '0' || line[j] == '1');
            AM[i][j] = line[j] - '0';
        }
    }

    graph->AM = AM;
    graph->name = gname;
    graph->vc = vc;
    graph->node = 0;
    createGraphFromAM(graph);
    fclose(fp);
    return graph;
}

/* How many times does val appear in array arr of size num? */
static inline size_t val_count(size_t num, const int arr[num], int val)
{
    assert(arr != 0);
    size_t count = 0;
    for (const int *end = arr + num; arr < end; arr++)
    {
        if (*arr == val)
            count++;
    }
    return count;
}

static void createGraphFromAM(Graph *graph)
{
    graph->node = (Node **)malloc(sizeof(*graph->node) * graph->vc);
    if (graph->node == 0)
        err_syserr("failed to allocate %zu bytes\n", sizeof(*graph->node) * graph->vc);

    for (int i = 0; i < graph->vc; i++)
    {
        graph->node[i] = (Node *)malloc(sizeof(Node));
        if (graph->node[i] == 0)
            err_syserr("failed to allocate %zu bytes\n", sizeof(Node));
        graph->node[i]->adjNum = val_count(graph->vc, graph->AM[i], 1);
        graph->node[i]->nodeNumber = i;
        size_t adj_size = sizeof(Node *) * (graph->node[i]->adjNum + 1);
        graph->node[i]->adjacent = (Node **)malloc(adj_size);
        if (graph->node[i]->adjacent == 0)
            err_syserr("failed to allocate %zu bytes\n", adj_size);
    }

    for (int i = 0; i < graph->vc; i++)
    {
        Node *node = graph->node[i];
        int adj = 0;
        for (int j = 0; j < graph->vc; j++)
        {
            if (graph->AM[i][j] == 1)
                node->adjacent[adj++] = graph->node[j];
        }
        node->adjacent[node->adjNum] = NULL;
    }
}

static void freeGraph(Graph *graph)
{
    for (int i = 0; i < graph->vc; i++)
    {
        free(graph->node[i]->adjacent);
        free(graph->node[i]);
    }
    free(graph->node);

    for (int i = 0; i < graph->vc; i++)
        free(graph->AM[i]);
    free(graph->AM);

    free(graph->name);
    free(graph);
}

static void printAllGraphNodeNumber(const Graph *graph)
{
    assert(graph != 0);
    printf("Nodes in the graph %s: %d\n", graph->name, graph->vc);
    for (int i = 0; i < graph->vc; i++)
    {
        printf("Node: %d - Adjacent Nodes: ", graph->node[i]->nodeNumber);
        const char *pad = "";
        for (int j = 0; j < graph->node[i]->adjNum; j++)
        {
            printf("%s%d", pad, graph->node[i]->adjacent[j]->nodeNumber);
            pad = ", ";
        }
        putchar('\n');
    }
}

int main(int argc, char **argv)
{
    err_setarg0(argv[0]);
    const char *filename = "data";
    if (argc == 2)
        filename = argv[1];
    Graph *graph = readGraphFromTxt(filename);
    if (graph != 0)
    {
        printAllGraphNodeNumber(graph);
        freeGraph(graph);
    }
    return 0;
}
one
AM
10
0100010011
1000110100
0000100001
0000000010
0110000100
1100000001
0000000001
0100100010
1001000101
1010011010
Nodes in the graph one: 10
Node: 0 - Adjacent Nodes: 1, 5, 8, 9
Node: 1 - Adjacent Nodes: 0, 4, 5, 7
Node: 2 - Adjacent Nodes: 4, 9
Node: 3 - Adjacent Nodes: 8
Node: 4 - Adjacent Nodes: 1, 2, 7
Node: 5 - Adjacent Nodes: 0, 1, 9
Node: 6 - Adjacent Nodes: 9
Node: 7 - Adjacent Nodes: 1, 4, 8
Node: 8 - Adjacent Nodes: 0, 3, 7, 9
Node: 9 - Adjacent Nodes: 0, 2, 5, 6, 8
Segmentation Fault , dynamically allocating a structure inside a dynamically allocated structure

Segmentation Fault , dynamically allocating a structure inside a dynamically allocated structure


By : Tim Moore
Date : March 29 2020, 07:55 AM
help you fix your problem Here is my complete code.... it's a big one,and thanks for your time. , malloc() doesn't call the constructor for your classes. Use new.
code :
student = new students[NStudents+1];
student[i].subjects = new subject[Subjects+1];
Seg faulting when accessing dynamically allocated memory in main (allocated in function), C

Seg faulting when accessing dynamically allocated memory in main (allocated in function), C


By : user1799135
Date : March 29 2020, 07:55 AM
I wish did fix the issue. matrix in CreateMatrix is a copy of the pointer matrix1. When you assign to matrix in that function, matrix1 in main is unaffected.
code :
int** CreateMatrix(int row, int col){

 int i, j;
 int **matrix = (int**)malloc(row* sizeof(int*));
 for (i = 0; i < row; i++) {
    matrix[i] = (int*)malloc(col* sizeof(int));
    for (j = 0 ; j < col; j++) {
        matrix[i][j] = 10;
        printf("i: %d, j: %d\n", i,j);
        printf("%d",matrix[i][j]);
    }
 }
 return matrix;
}

int main() {

// ...
   int **matrix1 = CreateMatrix(row, col);

// ...

return 0;
}
void CreateMatrix(int ***matrix, int row, int col){

    int i, j;
    *matrix = (int**)malloc(row* sizeof(int*));
    for (i = 0; i < row; i++) {
        (*matrix)[i] = (int*)malloc(col* sizeof(int));
        for (j = 0 ; j < col; j++) {
            (*matrix)[i][j] = 10;
            printf("i: %d, j: %d\n", i,j);
            printf("%d", (*matrix)[i][j]);
        }
    }
}


int main() {

    int **matrix1;
    CreateMatrix(&matrix1, 10, 10);
    printf("This should be 10 : %d",matrix1[0][0]);

    return 0;
}
Dynamically allocated structure array with an dynamically allocated structure array element

Dynamically allocated structure array with an dynamically allocated structure array element


By : goutham
Date : March 29 2020, 07:55 AM
To fix the issue you can do
In such case, how does the system will allocate memory for y before knowing the actual memory size of y[i].x.
Related Posts Related Posts :
  • Program works but outputs trailing garbage values
  • Letting 2 pointer pointing to same address
  • Different ways to print the two-dimensional array's contents
  • C Programming : Confusion between operator precedence
  • C code inside a loop not being executed
  • C - Weird symbols
  • C - Get pointer adress to string
  • how to start a function using a Struct?
  • Trying to tweak sscanf() to ignore \n and \t
  • How to find the inverse of a Rectangular Matrix in C using GSL
  • sizeof() showing different output
  • How to select/read/copy values after specific character in a string
  • Jump from bootloader generates exception
  • Array dropping values, picks up garbage
  • Swig: Syntax error in input(3)
  • multiple definition and making sure function is correctly written
  • MD4 openssl core dumped
  • Undefined-Behavior at its best, is it -boundary break? -bad pointer arithmetic? Or just -ignore of aliasing?
  • Why am i getting problem3.c:20:23: error: expected expression before ‘int’?
  • Right Justified Zero filled String in C
  • C Function with parameter without type indicator still works?
  • How to transmit data from an interrupt handler to an user application?
  • Why do I get the error "bash: ./a.out: Permission denied" when I execute a C program in Linux mint 15
  • syntax of sigchld and its declaration
  • error using g_idle_add() in C++, same thing works in C
  • why if else or nested if else are called single statement in C
  • How do I interpret this printf in C
  • load the functions of a shell script without executing it
  • Is FilterSendNetBufferLists handler a must for an NDIS filter to use NdisFSendNetBufferLists?
  • How to write to flash memory using inline assembly?
  • More Return Statements vs. More Indentation
  • How to show an image on a PictureBox from resource?
  • Having malloced some memory,I could't calculator the proper size of the memories I malloced.I don't know why
  • What is the main difference between integer pointer and character pointer?
  • Why are some functions declared extern and header file not included in source in Git source code?
  • what is the use of fflush(stdin) in c programming
  • Is it safe to return file File descriptor locally allocated from another function In C
  • Changing undefined values of an array
  • What does an empty parameter list mean?
  • using strtol on a string literal causing segmentation fault
  • Same structure objects memory overlap?
  • C-Linux-Any way to pass command "history" to Linux shell?
  • Using #define in defining string size C
  • How to use thread pool and message queues in Multithreaded Matrix Multiplication?
  • Can't find how to select path to run a C program
  • Automatic variable in C not initialized but given fixed value within loop
  • main() function defined without return type gives warning
  • Output of following code with integer, float, char variable
  • why buffer memory allocation error in opencl
  • Why am I getting this error during run-time?
  • Strange behaviour of the pow function
  • task in increment , decrement , printf() , why these are evaluated in this manner in C
  • 28 extra bytes in bss
  • Waiting for multiple events without polling
  • Why are my variables reporting as "undeclared identifier" when compiling?
  • Correct AddNode function but somehing happens when I printf
  • When I traverse in the splay tree, then now which one is root?
  • Data type conversion in Postfix evaluation
  • No output in terminal (Head First C)
  • Data writes over after realloc
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org