problem in memory allocation to struct variable [duplicate] - c

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;
}

Related

Using memcpy with bytes allocated on the heap [duplicate]

This question already has answers here:
Changing address contained by pointer using function
(5 answers)
Closed 2 years ago.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void *alloc_init(void *ptr, size_t size, void *val)
{
ptr = malloc(size);
memcpy(ptr, val, size);
return ptr;
}
int main()
{
int *a;
int val = 5;
int b = 5;
alloc_init(a, 4, &val);
printf("%d\n", *a);
return 0;
}
It's a very simple program - I wanted to test the alloc_init function. I expect 5 to be printed, but it's always 1. The function should be allocating memory for a variable(in this case) and assigning it a value passed to the function by copying it's bytes. What am I doing wrong?
Two ways to do this (both untested):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void alloc_init(void **ptr, size_t size, void *val)
{
*ptr = malloc(size);
memcpy(*ptr, val, size);
}
int main()
{
int *a;
int val = 5;
int b = 5;
alloc_init(&a, sizeof *a, &val);
printf("%d\n", *a);
return 0;
}
or
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void *alloc_init(size_t size, void *val)
{
void *ptr = malloc(size);
memcpy(ptr, val, size);
return ptr;
}
int main()
{
int *a;
int val = 5;
int b = 5;
a = alloc_init(sizeof *a, &val);
printf("%d\n", *a);
return 0;
}
You should probably prefer the 2nd approach. Passing an int** where a void** is expected is probably UB.

Why can't I create an opaque data type?

I'm trying to experiment with opaque data types to get an understanding of them. The main problem is that I keep getting an 'incomplete' error.
main.c
#include <stdio.h>
#include <stdlib.h>
#include "blepz.h"
int main()
{
setfnarp(GOO,5);
int loogaboo = getfnarp(GOO);
printf("%i", loogaboo);
return 0;
}
fnarpishnoop.c
#include "blepz.h"
struct noobza {
int fnarp;
};
void setfnarp(struct noobza x, int i){
x.fnarp = i;
};
int getfnarp(struct noobza x){
return x.fnarp;
};
blepz.h
struct noobza;
void setfnarp(struct noobza x, int i);
int getfnarp(struct noobza x);
struct noobza GOO;
I clearly don't understand something here and I was hoping someone could help me figure out how opaque data types are implemented if the whole point of them is that you have a hard time finding actual code for them.
Using a struct that you haven't declared the contents of gives an "incomplete type" error, as you have already mentioned.
Instead, use a pointer to the struct and a function that returns a pointer to the struct, like this:
struct noobza;
struct noobza *create_noobza(void);
void setfnarp(struct noobza *x, int i);
int getfnarp(struct noobza *x);
struct noobza *GOO;
...
#include <stdlib.h>
#include "blepz.h"
struct noobza {
int fnarp;
};
struct noobza *create_noobza(void)
{
return calloc(1, sizeof(struct noobza));
}
void setfnarp(struct noobza *x, int i){
x->fnarp = i;
};
int getfnarp(struct noobza *x){
return x->fnarp;
};
...
#include <stdio.h>
#include <stdlib.h>
#include "blepz.h"
int main()
{
GOO = create_noobza();
setfnarp(GOO,5);
int loogaboo = getfnarp(GOO);
printf("%i", loogaboo);
return 0;
}

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).

Return Pointer from function

I am new in C and literally trying to return pointer from my function to the pointer variable and have this "[Warning] assignment makes pointer from integer without a cast" no idea why compiler defines it as an int.
Can't declare my function before main as well, it throws this "undefined reference to `free_block'".
#include <stdio.h>
#include <stdlib.h>
struct block{
int num;
};
int main(int argc, char *argv[]) {
struct block *b;
b = free_block();
struct block *free_block(){
struct block *b = NULL;
return b;
}
return 0;
}
Thank you
Yea, my fault I know not too much about c syntax and had no idea about nested functions, soz.
But what could be wrong in this case:
I am trying to make my own memory allocator without using malloc or calloc functions. In my code I have the same Warning on the line with pointer = free_space_get(size);, here I have no more nested func(), my methods defined before main(), but still have no idea do I have to declare my functions or no, coz in the answer given to me it worked fine as soon as functions were defined before the main().
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct header{
size_t size;
struct header *next;
unsigned int free;
};
void *m_alloc(size_t size){
size_t total_size;
void *block;
struct header *pointer;
if(!size)
return NULL;
pointer = free_space_get(size);
if(pointer){
pointer->free = 0;
return (void*)(pointer + 1);
}
}
struct header *get_free_space(size_t size){
struct header *b = NULL;
return b;
}
int main() {
return 0;
}
Your code can be re-written as
#include <stdio.h>
#include <stdlib.h>
struct block{
int num;
};
struct block *free_block(){
struct block *b = NULL;
return b;
}
int main(int argc, char *argv[]) {
struct block *b;
b = free_block();
if(b == NULL) // Checking whether pointer is returned
printf("\n Recieved NULL \n");
return 0;
}

C program: Segmentation Fault [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am currently trying to solve a task, which is quite hard for me, a beginner to C, to handle and so i came to this point where I do not know what to do anymore.
My task is to implement polynomials with several functions....
The functions should be clear when you look at the code I think.
My exact problem is that i dont get a compiler error but a Segmentation Fault. I marked where my attempts to debug lead me to. But I have absolutely no clue on what I have to change. I hope someone can help me fix my code.
So here are the three code parts:
Number one: poly.c
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "poly.h"
struct poly_t {
unsigned degree;
int *coeffs;
};
//constructor: heap
poly_t *poly_alloc(unsigned degree){
poly_t *heap_p;
heap_p = malloc(sizeof(*heap_p)+(degree+1)*sizeof(int)); //or malloc(sizeof(*heap_p)*(degree+1)) furthermore not sure if degree or degree +1
}
//free heap
void poly_free(poly_t *p){
int *coeffs = p->coeffs;
free(coeffs);
free(p);
}
void poly_set_coeff(poly_t *p, unsigned deg, int coeff){
p->degree = deg;
p->coeffs += deg;
p->coeffs[deg] = coeff;
//does not work Segmentation Fault not sure what to do
//p->coeffs += deg;
//*p->coeffs = coeff;
printf("%d",*p->coeffs);
}
//different variations
poly_t *poly_linear(poly_t *p, int a1, int a0){
p->degree=1;
*p->coeffs=a1;
p->coeffs++;
*p->coeffs=a0;
p->coeffs--;
}
poly_t *poly_quadratic(poly_t *p, int a2, int a1, int a0){
p->degree=2;
*p->coeffs=a2;
p->coeffs++;
*p->coeffs=a1;
p->coeffs++;
*p->coeffs=a0;
p->coeffs-=2;
}
//evaluate using horner
int poly_eval(poly_t const *p, int x){
int d = p->degree;
int next;
int adr = *p->coeffs;
int *arr = p->coeffs;
int res = arr[d];
for(int i=0; i<=d; i++){
adr+=(d-i);
next = arr[adr];
adr-=(d-i);
res = res*x+next;
}
return res;
}
//constructor : .txt
poly_t *poly_alloc_d(){
//needs to be finished
}
Number Two: main.c
#include <stdlib.h>
#include <stdio.h>
#include "poly.h"
int main(int argc, char** argv){
if(argc<3){
fprintf(stderr, "syntax: %s x coeffs...", argv[0]);
return 1;
}
poly_t *p = poly_alloc(argc-3);
for(int i = 2; i<argc; i++){
int coeff = atoi (argv[i]);
poly_set_coeff(p, i-2, coeff);
}
return 0;//for debugging
int x=atoi(argv[1]);
int y=poly_eval(p,x);
poly_free(p);
printf("%d\n", y);
return 0;
}
And at last my header file:
poly.h
#ifndef POLY_H
#define POLY_H
/* unvollständiger Verbund */
typedef struct poly_t poly_t;
poly_t *poly_alloc(unsigned degree);
void poly_free(poly_t *p);
void poly_set_coeff(poly_t *p, unsigned deg, int coeff);
int poly_eval(poly_t const *p, int x);
#endif /* POLY_H */
I appreciate every help. I hope you can help me sort this out and please be patient with me a newbie to C...
Thanks in advance
You have not allocated or freed memory correctly, and the function didn't even return the pointer! I think you were trying to allocate one block of memory for the struct and the array it contains, but the struct does not contain an array: only a pointer to an array. You have to allocate them separately:
typedef struct {
unsigned degree;
int *coeffs;
} poly_t;
//constructor: heap
poly_t *poly_alloc(unsigned degree){
poly_t *heap_p;
heap_p = malloc(sizeof(*heap_p));
if (heap_p == NULL)
exit (1); // allocation error
heap_p->coeffs = malloc(degree * sizeof(int));
if (heap_p->coeffs == NULL)
exit (1); // allocation error
return heap_p;
}
//free heap
void poly_free(poly_t *p){
free(p->coeffs);
free(p);
}
There are other mistakes too, for example
p->coeffs += deg;
You mustn't play with the allocated memory pointer, you already did it correctly like this
p->coeffs[deg] = coeff;
although you can use an intermediate pointer if you want:
int *ptr = p->coeffs + deg;
*ptr = coeff;

Resources