Setting value to struct pointers [duplicate] - c

This question already has answers here:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
(5 answers)
Closed 2 years ago.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char** thingSize;
} Thing;
typedef struct {
Thing* thing;
} Game;
void load_array(Thing* thing) {
int i, j;
char **emptyThing = malloc(sizeof(char**));
emptyThing = malloc(sizeof(char*)*9);
for(i=0; i<9; i++) {
emptyThing[i] = malloc(sizeof(char)*9);
}
thing -> thingSize = emptyThing;
free(emptyThing);
}
int main(int argc, char* argv[]) {
Game* game;
load_array(game -> thing);
printf("HI");
}
I am getting a segmentation fault, I have found that the problem line is.
thing -> thingSize = emptyThing;
I am trying to set thingSize to be a 2d array equal to emptyThing.

As Fredrik said, the game pointer is not initialized to anything. It hold a garbage value, when dereferencing it, you will get a segfault.

Related

how to do malloc to array from struct [duplicate]

This question already has answers here:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
(5 answers)
Closed 8 months ago.
I have a stract and there should be an array whose size I don't know yet in main I try.
Here, for example, I created a define N, but in fact, I accept different data in different ways, including the array W.
I have to allocate memory for my array arr of structs.
#include <stdio.h>
#include <stdlib.h>
#define N 10
struct vector {
int size;
int *arr;
int length;
};
void main(void) {
int w[N] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
struct vector *ptr;
ptr->arr = (int *)malloc(sizeof(int) * N);
if (ptr->arr == NULL)
printf("Unable to allocate memory :(\n");
for (int i = 0; i < N; i++) {
ptr->arr[i] = w[i];
printf("%d ", ptr->arr[i]);
}
printf("\n");
}
Tried to do it in different ways but nothing works.
gives an error in the terminal:
Segmentation fault (core dumped).
please help me
you need to allocate the ptr first with your structure type.
right now ptr=Null, and you need it to point to a memory location with the size of your structure before you can allocate ptr->arr.
try this:
#include <stdio.h>
#include <stdlib.h>
#define N 10
typedef struct vector {
int size;
int *arr;
int length;
}vector_t;
void main(void)
{
int w[N]={1,2,3,4,5,6,7,8,9};
vector_t *ptr=(vector_t *)malloc(sizeof(vector_t));
ptr->arr=(int *) malloc( sizeof(int)*N );
/* ---- the rest of your code--- */
free(ptr->arr);
free(ptr);
}

Cannot pass struct to function by reference [duplicate]

This question already has answers here:
Allocate struct from function in C
(4 answers)
C struct pointer - how to return struct pointer from module?
(1 answer)
Closed 3 years ago.
I'm creating a very simple dictionary structure in C and I'm not able to properly pass it to dictAdd function by reference. Something goes wrong inside the function and structure values get corrupted. See screenshots below. Everything is fine when I step into line 18, but when I get inside the function to line 19 the structure fields being to show inappropriate values.
Line 18
Line 19
Dictionary.h
typedef struct DictionaryStruct
{
int *arr;
int arrLen;
} Dictionary;
Dictionary *dictCreate(int arrLen);
int dictAdd(Dictionary *dict, char *key, char *val);
Dictionary.c
#include "Utils.h"
#include "Dictionary.h"
Dictionary *dictCreate(int arrLen)
{
int *arr = createIntArray(arrLen);
for (int i = 0; i < arrLen; ++i)
{
arr[i] = '\0';
}
Dictionary dict;
dict.arr = arr;
dict.arrLen = arrLen;
return &dict;
}
int dictAdd(Dictionary *dict, char *key, char *val) {
int hash = getHash(key, dict->arrLen);
dict->arr[hash] = val;
}
Main.c
#include <stdio.h>
#include <stdlib.h>
#include "Utils.h"
#include "Dictionary.h"
int main() {
Dictionary *dictPtr = dictCreate(5);
dictAdd(dictPtr, "key1", "Hello");
char *value1 = dictGet(dictPtr, "key1");
printf("%s", value1);
printf("Press any key to exit\n");
getchar();
}
You're returning a pointer to a local. Dereferencing a pointer after the end of its target's lifetime is undefined behavior.
Your dictCreate should heap-allocate the Dictionary structure as well (in addition to heap-allocating the int array).

C Structure Initialization and Segmentation Fault [duplicate]

This question already has answers here:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
(5 answers)
Closed 3 years ago.
I have initialized a Structure through a Pointer and I have tried to get values using Pointer too. I am getting Segmentation Fault. Any Clue on it?
#include <stdio.h>
#include <stdlib.h>
int main(void){
struct MemData{
char* FileName;
int LastByteLength;
int ReadPointer;
int WritePointer;
char Data[ 512000];//MEMORY BLOCK SIZE: 500 KB
};
struct MemData* M;
M->FileName=(char*)"xaa";
M->LastByteLength=0;
M->ReadPointer=-1;
M->WritePointer=-1;
printf("\n%s", M->FileName);
printf("\n%d", M->LastByteLength);
printf("\n%d", M->ReadPointer);
printf("\n%d", M->WritePointer);
}
You need to allocate M.
#include <stdio.h>
#include <stdlib.h>
int main(void){
struct MemData{
char* FileName;
int LastByteLength;
int ReadPointer;
int WritePointer;
char Data[ 512000];//MEMORY BLOCK SIZE: 500 KB
};
struct MemData* M;
M = malloc(sizeof(*M));
M->FileName="xaa";
M->LastByteLength=0;
M->ReadPointer=-1;
M->WritePointer=-1;
printf("\n%s", M->FileName);
printf("\n%d", M->LastByteLength);
printf("\n%d", M->ReadPointer);
printf("\n%d", M->WritePointer);
free(M);
}
Try the above code, it should works.
As Broman suggested in comments I edited the answer removing the unnecessary "(char*)" cast as string literal already has the type char*

Why is this producing a segmentation fault? [duplicate]

This question already has answers here:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
(5 answers)
Closed 4 years ago.
I'm not sure why the following is producing a segmentation fault. I've defined a structure and I'm trying to store a value to it.
typedef struct {
int sourceid;
int destid;
} TEST_STRUCT;
void main( int argc, char *argv[] ) {
TEST_STRUCT *test;
test->sourceid = 5;
}
You declare a pointer to the type. You need to allocate memory for the pointer to point to:
#include <stdlib.h>
typedef struct {
int sourceid;
int destid;
} TEST_STRUCT;
int main(int argc, char *argv[]) {
TEST_STRUCT *test;
test = malloc(sizeof(TEST_STRUCT));
if (test) {
test->sourceid = 5;
free(test);
}
return 0;
}
Alternatively, you could declare the variable on the stack:
typedef struct {
int sourceid;
int destid;
} TEST_STRUCT;
int main(int argc, char *argv[]) {
TEST_STRUCT test;
test.sourceid = 5;
return 0;
}
test pointer is not pointing to any address(pointing some garbage) so it is hitting segV
TEST_STRUCT *test;
it is good practice to initialize NULL and before dereference it, check if (test != NULL) {}
then only dereference.
to solve this, first you need to create variable of TEST_STRUCT and assign address of it to test pointer or allocate memory using malloc/calloc and then try this

How do I correctly find out, what size the array of structs is? [duplicate]

This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 5 years ago.
I have the following minimal example and I don't get, why my struct sizes are wrong. I'm expecting the output to be 50, instead I get 1. What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
typedef struct prod {
char *x;
} prod_t;
typedef struct obj {
prod_t *things;
} obj_t;
#define LARGE_BUF 100
#define CHAR_BUF 20
obj_t *func1(obj_t *t) {
t->things = malloc(sizeof(prod_t) * LARGE_BUF);
for (uint16_t i = 0; i < 50; i++) {
t->things[i].x = malloc(sizeof(char) * CHAR_BUF);
t->things[i].x = "hello";
}
return t;
}
int main(int argc, char **argv) {
obj_t *var = malloc(sizeof(obj_t));
var = func1(var);
printf("%lu\n", sizeof(var->things)/sizeof(var->things[0]));
return 0;
}
Since I don't have the number of entries, the function generated for me (it's 50 now, but it could change dynamically), how do I free(..) this up?
Is the only option to introduce a field in the struct, to keep track of the actual array size?
Yes you will need to add another member to the struct. For example a string wrapper type keeps track of the number of characters in it:
typdef struct {
char *base;
size_t n;
} string;
Notice n is of size_t, not int.

Resources