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);
}
Related
This question already has an answer here:
C Passing Pointer to Pointer to a Function and Using malloc
(1 answer)
Closed 2 years ago.
I have a problem with realloc. Valgrind returns 8 bytes in 1 blocks are definitely lost in loss record 1 of 1. Whereas if I called the function allocate from main, it works. I don't understand what is the difference? It works if I put free(tab) inside the functionsth but I need to do something with tab inside main. Can anyone help find a solution?
#include <stdio.h>
#include <stdlib.h>
struct x{
int a;
char b;
};
void allocate( struct x **tab,int *size)
{
*size = 1+2*(*size);
*tab= realloc(*tab, (size_t) (*size) * sizeof (**tab));
}
void sth (struct x *tab, int *size)
{
//do something here
allocate(&tab, size);
}
int main(void)
{
int size=0;
struct x *tab=NULL;
sth(tab, &size);
//do sth here with tab
free(tab);
return 0;
}
The argument tab of the function sth is a copy of what is passed and change to that won't affect what is passed. Therefore, free(tab); in the main() function means free(NULL);. This is defined to do nothing and it won't contribute for avoiding memory leak. Pass pointers to what should be modified to have functions modify what are passed.
#include <stdio.h>
#include <stdlib.h>
struct x{
int a;
char b;
};
void allocate( struct x **tab,int *size)
{
*size = 1+2*(*size);
*tab= realloc(*tab, (size_t) (*size) * sizeof (**tab));
}
void sth (struct x **tab, int *size) // receive a pointer of struct x*
{
//do something here
// allocate(&(*tab), size);
allocate(tab, size);
}
int main(void)
{
int size=0;
struct x *tab=NULL;
sth(&tab, &size); // pass a pointer to what should be modified
//do sth here with tab
free(tab);
return 0;
}
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.
I am working on a project that deals with a struct and has various functions that manipulate the given struct.
I have started off with my initial function that just allocates the memory for the struct, and initialises each item in the struct and then returns a pointer to the struct. I have already defined the struct in my header file. I then have a main file that I will eventually use to run all my functions, however I am having trouble just running this first one, it seg faults every time I run it.
header:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <limits.h>
struct Double_Array{
double** array;
int rowsize;
int colsize;
};
struct Double_Array* double_array(int,int);
function:
#include "header.h"
struct Double_Array* double_array( int row, int col){
int i;
struct Double_Array* ptrDouble_Array;
ptrDouble_Array = (struct Double_Array*) malloc(sizeof(struct Double_Array));
ptrDouble_Array -> rowsize = row;
ptrDouble_Array -> colsize = col;
for(i=0;i< ptrDouble_Array -> colsize ; i++){
ptrDouble_Array -> array[i] = malloc((sizeof(double))*(row));
}
return(ptrDouble_Array);
}
mainline:
#include "header.h"
int main(){
srand(time(0));
printf("running");
int i;
int j;
struct Double_Array* ptr;
ptr = double_array( 5, 5);
for(i=0;i<5;i++){
free(ptr->array[i]);
}
free(ptr);
return(0);
}
I've spent a while looking for possible issues, but everything looks logically correct to me.
What is causing the Seg fault
You're allocating space for each array[i], but you never allocate space for array. So ptrDouble_Array->array[i] is dereferencing an uninitialized pointer, which causes the segfault.
Add the allocation:
ptrDouble_Array->array = malloc((sizeof(double *))*(col));
for(i=0;i< ptrDouble_Array->colsize ; i++){
ptrDouble_Array->array[i] = malloc((sizeof(double))*(row));
}
And don't forget to free it:
for(i=0;i<5;i++){
free(ptr->array[i]);
}
free(ptr->array);
free(ptr);
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).
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;