Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have been trying to call this function, but I keep getting the error "identifier not found" (yes, I know my variable names aren't the most practical).
#include <stdio.h>
#include <stdlib.h>
typedef struct _POOL
{
int size;
void* memory;
} Pool;
int main()
{
printf("Enter the number of bytes you want to allocate\n");
int x = getchar();
allocatePool(x);
return 0;
}
Pool* allocatePool(int x)
{
Pool* p = (Pool*)malloc(x);
return p;
}
Maybe what you want to do should look like this:
#include <stdio.h>
#include <stdlib.h>
typedef struct pool
{
int size;
void* memory;
} pool;
pool allocatePool(int x);
int main (int argc, char *argv[])
{
int x = 0;
pool *p = NULL;
printf("enter the number of bytes you want to allocate//>\n");
if (scanf("%d", &x) == 1 && x > 0 && (p = allocatePool(x)) != NULL)
{
// Do something using p
// ...
// Treatment is done, now freeing memory
free(p->memory);
free(p);
p = NULL; // Not useful right before exiting, but most often good practice.
return 0;
}
else
{
// Show a message error or do an alternative treatment
return 1;
}
}
pool allocatePool(int x)
{
pool *p = malloc(sizeof(pool));
if (p != NULL)
{
p->memory = malloc(x);
p->size = (p->memory == NULL) ? 0 : x;
}
return p;
}
I think your program should look like this:
#include <stdio.h>
#include <stdlib.h>
typedef struct _Pool
{
int size;
void* memory;
} Pool;
Pool* allocatePool(int x)
{
static Pool p;//no pointer here you also need memory for your integer or you have to allocate memory for the integer too
p.size=x;
p.memory=malloc(x);//just allocate memory for your void pointer
return &p;//return the adress of the Pool
}
int main()
{
printf("enter the number of bytes you want to allocate//>\n");
int x;
scanf("%d", &x);//if you use getchar() for reading you pass the ascii value of the number not the normal number
allocatePool(x);
return 0;
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am writing a vm from a tutorial and I keep getting segmentation fault. gdb is not giving me any info accept for that it is in int main() but I see nothing wrong, of course I have a bad eye for things that are wrong so if one of you smart people can help me that would be great
vm.c (I fixed the indentation)
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
typedef struct OBJECT_t {
uint8_t type;
union {
uint8_t u8;
int8_t i8;
uint32_t u32;
int32_t i32;
void *ptr;
};
} OBJECT;
typedef struct STACK_t {
int top;
int size;
OBJECT *stack;
} STACK;
typedef uint8_t* (*instruction)(uint8_t *, STACK *);
STACK stack_new(int size) {
STACK s;
s.top = 0;
s.size = size;
s.stack = (OBJECT *)malloc(sizeof(OBJECT) * size);
return s;
}
int stack_push(STACK *s, OBJECT o){
s->stack[s->top++] = o;
return s->top;
}
OBJECT stack_pop(STACK *s){
return s->stack[--(s->top)];
}
OBJECT stack_peek(STACK *s) {
return s->stack[s->top - 1];
}
void usage(){
printf("usage: vm <file>\n");
exit(1);
}
uint8_t *load_file(char *filename) {
FILE *f;
int size;
uint8_t *code = NULL;
struct stat st;
if((f = fopen(filename, "r"))) {
fstat(fileno(f), &st);
code = (uint8_t *)malloc(st.st_size);
fread((void *)code, 1, st.st_size, f);
}else {
printf("ERROR: cannot open file %s\n", filename);
usage();
}
return code;
}
uint8_t *op_nop(uint8_t *ip, STACK *s){
return ip + 1;
}
uint8_t *op_push_char(uint8_t *ip, STACK *s){
OBJECT o;
o.type = 'c';
o.u8 = *(ip + 1);
stack_push(s, o);
return ip + 2;
}
uint8_t *op_emit(uint8_t *ip, STACK *s){
OBJECT o = stack_pop(s);
putchar(o.u8);
return ip + 1;
}
int main(int argc, char **argv){
uint8_t *code;
uint8_t *ip;
STACK data;
instruction ops[256];
if(argc != 2){
usage();
}
for(int i=0;i<256;i++){
ops[i] = op_nop;
}
ops['c'] = op_push_char;
code = load_file(argv[1]);
data = stack_new(1024);
ip = code;
while(*ip != 'h'){
ip = ops[*ip](ip, &data);
}
return 0;
}
my program
hello.sp
c
c!cdclcrcocwc coclclcecHeeeeeeeeeeeeeh
this is my gdb output
Program received signal SIGSEGV, Segmentation fault.
0x00000000004014a6 in main ()
after fixing the problems discussed in the comments to the question:
when compiling AND when linking, use the parameter: -ggdb3 Which will:
result in a much larger object files and much larger executable.
will have the maximum amount of information for the gdb debugger.
Among other things, gdb will then display the line numbers.
then use the bt command to display the back trace of the stack at the time of a crash, so you know exactly how the code got to the crash.
Feel like im taking crazy pills just trying to do literally the simplest stuff I can imagine in C. Any help would be extremely appreciated. why does this work?
#include <stdio.h>
#include <stdlib.h>
#define Q_LIMT 100
typedef struct servers
{
int id;
int num_in_Q;
int server_status;
}SERVER;
void initialize(SERVER *s);
void initialize(SERVER *s)
{
int i=0,j=0;
for(i=0; i<2; i++) { //i=0; i=1
s[i].id = i; // 0, 1
s[i].num_in_Q = i*i + 1; // 1, 2
s[i].server_status = i+i + 2; // 2, 4
} // the bracket was missing
}
int main()
{
int i;
SERVER serv[2];
initialize(serv);
for(i=0; i<2; i++) {
printf("server[%d].id = %d\n", i, serv[i].id);
printf("server[%d].num_in_Q = %d\n", i, serv[i].num_in_Q);
but this throws away the initialized struct?
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
'''
int POINTERS_PER_INODE = 5;
struct Inode {
int valid;/* 0 == invalid, 1 == valid*/
int size;
int Blocks [5];
};
int InodeToString(char * InodeString, struct Inode iNode){
char * blockBuffer;
sprintf(InodeString, "%d", iNode.valid);
int i;
for (i = 0; i < POINTERS_PER_INODE; i++){
blockBuffer = malloc(8);
sprintf(blockBuffer, "%d", iNode.Blocks[i]); //no valid pointers yet
strcat(InodeString,blockBuffer);
free(blockBuffer);
}
return 0;
}
int initializeInode(struct Inode iNode){
int i;
for (i = 0; i < POINTERS_PER_INODE; i++){
iNode.Blocks[i] = -1; //no valid pointers yet
}
iNode.valid = 0; //initialized as invalid inode
return 0;
}
int main() {
struct Inode iNode1;
initializeInode(iNode1);
char * InodeString;
InodeString = malloc(20);
InodeToString(InodeString, iNode1);
printf("%s", InodeString);
free(InodeString);
iNode1.valid = 1;
InodeString = malloc(20);
InodeToString(InodeString, iNode1);
printf("%s", InodeString);
return 0;
}
This is test code btw, so the includes probably dont make sense. stack overflow says I dont have enough details so I guess I have to keep typing sentences. Let me know if theres any details that would make this more clear. its for a basic super simplified file system simulation project. it seemed in a previous version when I initialized the inode outside of the function, I was able to pass the string into the string function, assign it values, not use it as the return value and still end up on the other side of the function with an updated string.
As is normal in C, arguments to a function are passed by value. The object called iNode in initializeInode is local to that function, and changes to it have no effect on any other object in the program. If you want a function to modify an object that's local to the caller, you have to pass a pointer to it, and dereference that pointer to get at the caller's object.
So what you probably want is:
int initializeInode(struct Inode *iNode){
int i;
for (i = 0; i < POINTERS_PER_INODE; i++){
iNode->Blocks[i] = -1; //no valid pointers yet
}
iNode->valid = 0; //initialized as invalid inode
return 0;
}
int main() {
struct Inode iNode1;
initializeInode(&iNode1);
// ...
}
This question already has answers here:
Assignment of function parameter has no effect outside the function
(2 answers)
How do I modify a pointer that has been passed into a function in C?
(7 answers)
Closed 2 years ago.
Don't mind my code writing style. I specifically created this for testing purposes...
Now to the problem:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define EMB 31
#define NAME_MAX 50
struct TRIP {
char TRIP_NAME[EMB];
int TRIP_TIME;
};
struct DATE {
int day;
int month;
int year;
};
struct TRIP_INFORMATION {
char TRIP_NUMBER[EMB];
char EMBARKATION_POINT[EMB];
char SPECIFIC_DROPOFFPOINT[EMB];
char EXIT_DROPOFFPOINT[EMB];
struct DATE TRIP_DATE;
struct TRIP SPECIFIC_TRIP;
};
struct EMBARKATION_CARD{
//struct DATE TRIP_DATE;
char NAME[NAME_MAX];
int ID_NUMBER;
int PRIORITY_NUMBER;
//int TRIP_TIME;
//char EMBARKATION_POINT[EMB];
//char DROPOFFPOINT[EMB];
struct TRIP_INFORMATION TRIP_INFORMATION;
};
This is for the reference of declaration.
int BeginEmbarkationProcess(int *PASSENGER_COUNT, struct EMBARKATION_CARD * PASSENGER_TO_SAVE, int curr_day, int curr_month, int curr_year){
//struct EMBARKATION_CARD * P;
if(*PASSENGER_COUNT>1){
PASSENGER_TO_SAVE = realloc(PASSENGER_TO_SAVE, *PASSENGER_COUNT * sizeof(struct EMBARKATION_CARD));
if(PASSENGER_TO_SAVE == NULL){
puts("PASSENGER_TO_SAVE VARIABLE = HAS NOT ALLOCATED MEMORY");
return -1;
}
}
if(PASSENGER_TO_SAVE==NULL){
puts("PASSENGER TO SAVE POINTER HAS UNABLE TO ALLOCATE MEMORY");
return -1;
}
int x = 0;
for(x=0;x<*PASSENGER_COUNT;x++){
((PASSENGER_TO_SAVE+x))->ID_NUMBER = (x+1)*30;
((PASSENGER_TO_SAVE+x))->PRIORITY_NUMBER = (x+1)*17;
}
for(x=0;x<*PASSENGER_COUNT;x++){
printf("%d %d\n", (PASSENGER_TO_SAVE+x)->ID_NUMBER , (PASSENGER_TO_SAVE+x)->PRIORITY_NUMBER);
}
*PASSENGER_COUNT = *PASSENGER_COUNT + 1;
int r;
printf("ENTER -1 TO TERMINATE THIS LOOP\n");
scanf("%d", &r);
return r;
}
int main(){
//doIt();
struct EMBARKATION_CARD* E = malloc(sizeof(struct EMBARKATION_CARD));
int ct = 1;
int s = BeginEmbarkationProcess(&ct, E, 3, 3, 2020);
while(s!=-1){
s = BeginEmbarkationProcess(&ct, E, 3, 3, 2020);
}
return s;
}
Since I copy pasted this (and removed some commented out lines but eventually got tired of it), this copy pasted code might have some syntax error. Ignore those syntax error please.
The issue is that realloc WILL keep returning NULL.
This prevents me from readjusting it.
Can someone tell me what the hell is going on.
I know I may have made some errors here but I want to learn about it.
Yes I am just a student learning C language.
Okay, so the problem concerns adding values through function to structure. Honestly, I couldn't solve the problem (spent a lot of time trying), so I am asking for your help. While executing the program, I get a segmentation fault. It occurs while using the variables from stack stos.
typedef struct e {
int zaglebienie[100];
char *nazwa_funkcji[100];
int poz;
} *stack;
void put_on_fun_stack(int par_level, char *funame, stack stos) {
int i = stos->poz;
stos->zaglebienie[i] = par_level;
char *funkcja = strdup(funame);
stos->nazwa_funkcji[i] = funkcja;
stos->poz++;
}
int main() {
char *p = "makro";
stack stos;
stos->zaglebienie[0] = 0;
put_on_fun_stack(1, p, stos);
return 0;
}
You're declaring a pointer to stack but you're not allocating any memory to it.
And as already mentioned in the comments, using typedef with with a pointer will unnecessarily complicate your life.
So I suggest you create the struct stack and then in main declare a pointer to stack and allocate memory for it, somewhat like this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct e {
int zaglebienie[100];
char *nazwa_funkcji[100];
int poz;
} stack;
void put_on_fun_stack(int par_level, char *funame, stack *stos)
{
int i = stos->poz;
stos->zaglebienie[i] = par_level;
char *funkcja = strdup(funame);
stos->nazwa_funkcji[i] = funkcja;
stos->poz++;
}
int main(void)
{
char *p = "makro";
// calloc to initialize stos variables to 0
stack *stos = calloc(sizeof(stack), 1);
printf("stos->poz before: %d\n", stos->poz);
put_on_fun_stack(1, p, stos);
printf("stos->poz after: %d\n", stos->poz);
printf("stos->nazwa_funkcji[0]: %s\n", stos->nazwa_funkcji[0]);
free(stos->nazwa_funkcji[0]);
free(stos);
return 0;
}
Output:
stos->poz before: 0
stos->poz after: 1
stos->nazwa_funkcji[0]: makro
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;