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*
Related
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);
}
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.
This question already has answers here:
How do I modify a pointer that has been passed into a function in C?
(7 answers)
Closed 2 years ago.
Below is minimal, reproducible code for my problem. I don't know why this piece of code prints 1 as I expect to print 512.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct ser_buff_ {
#define SERIALIZE_BUFFER_DEFAULT_SIZE 512
void *b;
int size;
int next;
}ser_buff_t;
void
init_serialized_buffer(ser_buff_t *b){
b = (ser_buff_t*)calloc(1, sizeof(ser_buff_t));
b->b = calloc(1, SERIALIZE_BUFFER_DEFAULT_SIZE);
b->size = SERIALIZE_BUFFER_DEFAULT_SIZE;
b->next = 0;
}
int main(void){
ser_buff_t *b;
init_serialized_buffer(b);
printf("%d\n", b->size);
return 0;
}
#UnholySheep is right. You need to pass the reference to the first pointer in the init_serialized_buffer() in order to be able to modify it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct ser_buff_ {
#define SERIALIZE_BUFFER_DEFAULT_SIZE 512
void *b;
int size;
int next;
}ser_buff_t;
void
init_serialized_buffer(ser_buff_t **b){
*b = (ser_buff_t*)calloc(1, sizeof(ser_buff_t));
(*b)->b = calloc(1, SERIALIZE_BUFFER_DEFAULT_SIZE);
(*b)->size = SERIALIZE_BUFFER_DEFAULT_SIZE;
(*b)->next = 0;
}
int main(void){
ser_buff_t *b;
init_serialized_buffer(&b);
printf("%d\n", b->size);
return 0;
}
I'm trying to write a data structure with two elements, and then defining a variable of that type struct. However, after initializing the variable in the main function, I'm getting segmentation fault and I don't know why.
#include <stdio.h>
#include <string.h>
struct AnimalSizes {
char stringName[50];
double sizeLength;
} animalSizes[2];
int main()
{
struct AnimalSizes *snakes;
strcpy(snakes[0].stringName,"Anaconda");
snakes[0].sizeLength=3.7;
strcpy(snakes[1].stringName,"Python");
snakes[1].sizeLength= 2.4;
printf("%c", *snakes[0].stringName);
printf("%lf", snakes[0].sizeLength);
printf("%c", *snakes[1].stringName);
printf("%lf", snakes[1].sizeLength);
return 0;
}
You try to strcpy to destination where is no allocated memory. That is undefined behavior.
You should first allocate enough memory to hold two AnimalSizes instances:
struct AnimalSizes *snakes;
snakes = malloc(2 * sizeof(struct AnimalSizes));
Also, here
printf("%c", snakes[0].stringName);
you are trying to output the first character of stringName. I assume, what you rather want to do is to output whole string with %s.
You've declared a pointer to a struct AnimalSizes, and you have declared an array struct AnimalSizes[2], but you have not made the pointer point to this array:
int main()
{
struct AnimalSizes *snakes = &animalSizes[0];
...
}
Alternatively, you may choose to not declare a global variable, rather choosing to allocate memory in main:
#include <stdlib.c>
#include <stdio.h>
#include <string.h>
struct AnimalSizes {
char stringName[50];
double sizeLength;
};
int main()
{
struct AnimalSizes *snakes = (struct AnimalSizes*) malloc(2*sizeof(struct AnimalSizes));
strcpy(snakes[0].stringName,"Anaconda");
snakes[0].sizeLength=3.7;
strcpy(snakes[1].stringName,"Python");
snakes[1].sizeLength= 2.4;
printf("%c", *snakes[0].stringName);
printf("%lf", snakes[0].sizeLength);
printf("%c", *snakes[1].stringName);
printf("%lf", snakes[1].sizeLength);
free(snakes);
return 0;
}
the following proposed code:
eliminates any need for malloc() and free()
performs the desired functionality
separates the definition of the struct from any instance of the struct.
inserts some spacing between the first letter of the snake name and the 'size' of the snake, for readability
applies certain other changes to the code for 'human' readability
and now the proposed code:
#include <stdio.h>
#include <string.h>
struct AnimalSizes
{
char stringName[50];
double sizeLength;
};
int main( void )
{
struct AnimalSizes snakes[2];
strcpy(snakes[0].stringName,"Anaconda");
snakes[0].sizeLength=3.7;
strcpy(snakes[1].stringName,"Python");
snakes[1].sizeLength= 2.4;
printf("%c ", snakes[0].stringName[0]);
printf("%lf\n", snakes[0].sizeLength);
printf("%c ", snakes[1].stringName[0]);
printf("%lf\n", snakes[1].sizeLength);
return 0;
}
a run of the proposed code outputs:
A 3.700000
P 2.400000
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).