I'm fully prepared to be told that I'm doing something stupid/wrong; this is what I expect.
I'm getting a feel for structures and coming a cropper when it comes to accessing the fields from the pointers. Code to follow.
matrix.h:
#ifndef MATRIX_H_INCLUDED
#define MATRIX_H_INCLUDED
#include <stdlib.h>
typedef struct
{
size_t size;
int* vector;
} vector_t;
#endif // MATRIX_H_INCLUDED
main.c:
#include <stdio.h>
#include <stdlib.h>
#include "matrix.h"
vector_t* vector_new(size_t size)
{
int vector[size];
vector_t v;
v.size = size;
v.vector = vector;
return &v;
}
int main(int argc, char* argv[])
{
vector_t* vec = vector_new(3);
printf("v has size %d.\n", vec->size);
printf("v has size %d.\n", vec->size);
return EXIT_SUCCESS;
}
So this is a very simple program where I create a vector structure of size 3, return the pointer to the structure and then print its size. This, on the first print instance is 3 which then changes to 2686668 on the next print. What is going on?
Thanks in advance.
You are returning a pointer to a local variable v from vector_new. This does not have a slightest chance to work. By the time vector_new returns to main, all local variables are destroyed and your pointer points to nowhere. Moreover, the memory v.vector points to is also a local array vector. It is also destroyed when vector_new returns.
This is why you see garbage printed by your printf.
Your code has to be completely redesigned with regard to memory management. The actual array has to be allocated dynamically, using malloc. The vector_t object itself might be allocated dynamically or might be declared as a local variable in main and passed to vector_new for initialization. (Which approach you want to follow is up to you).
For example, if we decide to do everything using dynamic allocation, then it might look as follows
vector_t* vector_new(size_t size)
{
vector_t* v = malloc(sizeof *v);
v->size = size;
v->vector = malloc(v->size * sizeof *v->vector);
return v;
}
(and don't forget to check that malloc succeeded).
However, everything that we allocated dynamically we have to deallocate later using free. So, you will have to write a vector_free function for that purpose.
Complete re-write of answer to address your question, and to provide alternate approach:
The code as written in OP will not compile: &v is an illegal return value.
If I modify your code as such:
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
size_t size;
int* vector;
} vector_t;
vector_t* vector_new(size_t size)
{
int vector[size];
vector_t v, *pV;
pV = &v;
pV->size = size;
pV->vector = vector;
return pV;
}
int main(int argc, char* argv[])
{
vector_t* vec = vector_new(3);
printf("v has size %d.\n", vec->size);
printf("v has size %d.\n", vec->size);
getchar();
return EXIT_SUCCESS;
}
It builds and runs, but returns unintended values for vec->size in main() due to the local scope of that variable in the function vector_new.
Recommend creating globally visible instance of your struct, and redefine vector_new() to int initVector(void):
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
typedef struct
{
size_t size;
int* vector;
} vector_t;
vector_t v, *pV;//globally visible instance of struct
int initVector(void)
{
int i;
pV->size = SIZE;
pV->vector = calloc(SIZE, sizeof(int));
if(!pV->vector) return -1;
for(i=0;i<SIZE;i++)
{
pV->vector[i] = i;
}
return 0;
}
int main(int argc, char* argv[])
{
int i;
pV = &v; //initialize instance of struct
if(initVector() == 0)
{
printf("pV->size has size %d.\n", pV->size);
for(i=0;i<SIZE;i++) printf("pV->vector[%d] == %d.\n", i, pV->vector[i]);
}
getchar(); //to pause execution
return EXIT_SUCCESS;
}
Yields these results:
You still need to write a freeVector function to undo all the allocated memory.
Related
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct individual {
char name[32];
int stats[7];
char role;
};
void create_array(struct individual **array){
*array = malloc(sizeof(struct individual)); //allocate initial memory space
}
void resize_array(struct individual **array, unsigned char num) {
printf("%d\n", *array);
*array = realloc(*array, num * sizeof(struct individual));
printf("%d\n", *array);
printf("resize success\n");
}
void problem(struct individual **f_array, unsigned char *f_num) {
*f_num = 2;
printf("%d\n", *f_array);
resize_array(f_array, *f_num);
printf("%d\n", *f_array);
strcpy(f_array[*f_num - 1]->name, "test value"); //CRASH LINE
}
int main() {
unsigned char f_num = 0;
struct individual *f_array;
create_array(&f_array);
problem(&f_array, &f_num);
}
This code crashes on the line marked "CRASH LINE". While it is not shown here, doing this same code setting (*f_num = 1) does not result in an error. While passing *f_array as itself (with appropriate alterations to the code in problem) does not result in an error, the values given after problem is exited result in nonsense being given, as the pointer reverts to it's pre-resize state. Any help appreciated.
The problem is the line accessing that value.
The line should read like this:
strcpy((*f_array)[*f_num - 1].name, "test value"); // doesn't crash any more :)
To break it down a little bit:
f_array is a pointer to the array of structs, need to dereference it before indexing
[*f_num - 1] accesses element 1 of the array.
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;
}
When I use this code I would like to turn to every element of array of structures like this:
array[0]->X;
array[1]->X;
I tried everything I could, but in all cases I've had Segmentation fault. What am I doing wrong?
Please look at blocks between #if 0 #endif
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <inttypes.h>
typedef struct
{
double X;
double Y;
} ArrayOfStructures;
typedef struct
{
uint_fast64_t length;
ArrayOfStructures **array;
} Points;
typedef struct
{
Points *points;
} Config;
void add_new_array(Config *conf)
{
printf("conf=%p\n",conf);
printf("conf->points=%p\n",conf->points);
printf("conf->points->length=%zu\n",conf->points->length);
printf("conf->points->array=%p\n",conf->points->array);
#if 0
ArrayOfStructures *temp = (ArrayOfStructures*)calloc(conf->points->length,sizeof(ArrayOfStructures));
printf("temp=%p\n",temp);
// Segmentation fault
*conf->points->array = temp;
#else
conf->points->array = (ArrayOfStructures **)calloc(conf->points->length,sizeof(ArrayOfStructures *));
#endif
printf("conf->points->array=%p\n",conf->points->array);
}
void another_function(Config *conf)
{
conf->points->length = 1;
add_new_array(conf);
conf->points->array[0]->X = 0.1;
conf->points->array[0]->Y = 0.2;
printf("The result: X=%.12f, Y=%.12f, length=%zu\n",conf->points->array[0]->X,conf->points->array[0]->Y,conf->points->length);
}
void some_function(Config * conf)
{
// To pass the structure to another function
another_function(conf);
}
int main(void)
{
// Stack's allocated memory
Config conf_;
Config *conf = &conf_;
memset(conf,0x0,sizeof(Config));
// Stack's allocated memory
Points points;
memset(&points,0x0,sizeof(Points));
conf->points = &points;
some_function(conf);
return(EXIT_SUCCESS);
}
Compiled using:
gcc -D_SVID_SOURCE -g -ggdb -ggdb1 -ggdb2 -ggdb3 -O0 -DDEBUG -std=c11 -Wall --pedantic arryay.c -o array
I tried to find answers for handling a double pointer, but everything is very confusing.
You're fairly close to what you want according to your comment.
Using array of structures
Here's an adaptation of your code. The primary change is use ArrayOfStructs *array instead of using a pointer-to-pointer. Also, because you've decided to use uint_fast64_t for a data type, you have to use PRIuFAST64 from <inttypes.h> to get the correct format string. It would be better to change that to size_t; you aren't going to spot the performance difference on any reasonable system (but the code uses the format PRIuFAST64).
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <inttypes.h>
typedef struct
{
double X;
double Y;
} ArrayOfStructures;
typedef struct
{
uint_fast64_t length;
ArrayOfStructures *array;
} Points;
typedef struct
{
Points *points;
} Config;
static
void add_new_array(Config *conf)
{
printf("conf=%p\n", conf);
printf("conf->points=%p\n", conf->points);
printf("conf->points->length=%" PRIuFAST64 "\n", conf->points->length);
printf("conf->points->array=%p\n", conf->points->array);
ArrayOfStructures *temp = calloc(conf->points->length, sizeof(ArrayOfStructures));
printf("temp=%p\n", temp);
conf->points->array = temp;
printf("conf->points->array=%p\n", conf->points->array);
}
static
void another_function(Config *conf)
{
conf->points->length = 1;
add_new_array(conf);
conf->points->array[0].X = 0.1;
conf->points->array[0].Y = 0.2;
printf("The result: X=%.12f, Y=%.12f, length=%" PRIuFAST64 "\n",
conf->points->array[0].X, conf->points->array[0].Y, conf->points->length);
}
static
void some_function(Config *conf)
{
// To pass the structure to another function
another_function(conf);
}
int main(void)
{
// Stack's allocated memory
Config conf_;
Config *conf = &conf_;
memset(conf, 0x0, sizeof(Config));
// Stack's allocated memory
Points points;
memset(&points, 0x0, sizeof(Points));
conf->points = &points;
some_function(conf);
return(EXIT_SUCCESS);
}
When run, this produces:
conf=0x7ffeed6883f8
conf->points=0x7ffeed688400
conf->points->length=1
conf->points->array=0x0
temp=0x7fef13c02a80
conf->points->array=0x7fef13c02a80
The result: X=0.100000000000, Y=0.200000000000, length=1
It doesn't crash. I've not run it under Valgrind. It will report leaks for the allocated memory.
Your type name ArrayOfStructures for a type that has no array in it seems wildly inappropriate. I'd've expected that to be given a name such as Point. I assume your Config structure has been minimized for this question (if so, thank you). If not, then the structure holding a single pointer to another structure is not giving you any benefit. It is just slowing down your access to the data — vastly outweighing any benefit from using uint_fast64_t instead of size_t. You'll need to be careful about your allocation of memory for the Config structure; you can't simply free everything inside the Config and its child structures at the moment.
Using array of pointers to structures
This is very similar to the last code, but you need an extra set of memory allocations. I've made that into a loop since the only reason for using this design is to allow you to allocate the pointed at structures separately. Otherwise, it is just needlessly complex. I've made a few minor cleanups; there are more improvements possible. I've added a structure dumper function, dump_points(), which I can and do use to print values at different points.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <inttypes.h>
typedef struct
{
double X;
double Y;
} ArrayOfStructures;
typedef struct
{
size_t length;
ArrayOfStructures **array;
} Points;
typedef struct
{
Points *points;
} Config;
static void dump_points(const char *tag, const Points *points)
{
printf("%s (%zu, %p)\n", tag, points->length, (void *)points);
for (size_t i = 0; i < points->length; i++)
printf("%zu: (%.12f, %.12f) %p\n", i, points->array[i]->X, points->array[i]->Y,
(void *)points->array[i]);
}
static
void add_new_array(Config *conf)
{
printf("conf=%p\n", (void *)conf);
printf("conf->points=%p\n", (void *)conf->points);
printf("conf->points->length=%zu\n", conf->points->length);
printf("conf->points->array=%p\n", (void *)conf->points->array);
conf->points->array = calloc(conf->points->length, sizeof(conf->points->array[0]));
for (size_t i = 0; i < conf->points->length; i++)
conf->points->array[i] = calloc(1, sizeof(conf->points->array[i][0]));
printf("conf->points->array=%p\n", (void *)conf->points->array);
printf("conf->points->array[0]=%p\n", (void *)conf->points->array[0]);
dump_points("Inside add new array", conf->points);
}
static
void another_function(Config *conf)
{
conf->points->length = 3;
add_new_array(conf);
conf->points->array[0]->X = 0.1;
conf->points->array[0]->Y = 0.2;
conf->points->array[1]->X = 1.1;
conf->points->array[1]->Y = 1.2;
conf->points->array[2]->X = 2.1;
conf->points->array[2]->Y = 2.2;
dump_points("Inside another function", conf->points);
}
static
void some_function(Config *conf)
{
// To pass the structure to another function
another_function(conf);
dump_points("Inside some function", conf->points);
}
int main(void)
{
// Stack's allocated memory
Config conf_;
Config *conf = &conf_;
memset(conf, 0x0, sizeof(Config));
// Stack's allocated memory
Points points;
memset(&points, 0x0, sizeof(Points));
conf->points = &points;
some_function(conf);
dump_points("Inside main", conf->points);
return(EXIT_SUCCESS);
}
Sample output (macOS 10.14.5 Mojave; GCC 9.1.0):
conf=0x7ffee6f6b408
conf->points=0x7ffee6f6b410
conf->points->length=3
conf->points->array=0x0
conf->points->array=0x7f9c0a402a70
conf->points->array[0]=0x7f9c0a402a90
Inside add new array (3, 0x7ffee6f6b410)
0: (0.000000000000, 0.000000000000) 0x7f9c0a402a90
1: (0.000000000000, 0.000000000000) 0x7f9c0a402aa0
2: (0.000000000000, 0.000000000000) 0x7f9c0a402ab0
Inside another function (3, 0x7ffee6f6b410)
0: (0.100000000000, 0.200000000000) 0x7f9c0a402a90
1: (1.100000000000, 1.200000000000) 0x7f9c0a402aa0
2: (2.100000000000, 2.200000000000) 0x7f9c0a402ab0
Inside some function (3, 0x7ffee6f6b410)
0: (0.100000000000, 0.200000000000) 0x7f9c0a402a90
1: (1.100000000000, 1.200000000000) 0x7f9c0a402aa0
2: (2.100000000000, 2.200000000000) 0x7f9c0a402ab0
Inside main (3, 0x7ffee6f6b410)
0: (0.100000000000, 0.200000000000) 0x7f9c0a402a90
1: (1.100000000000, 1.200000000000) 0x7f9c0a402aa0
2: (2.100000000000, 2.200000000000) 0x7f9c0a402ab0
It's reassuring to see that the data is not corrupted as it is passed back up the chain of functions.
You don't seem to initialize length to a meaningful value. Therefore you don't actually allocate memory, since you call calloc() with the first argument being zero.
(Disclaimer: I haven't tested the code, but that seems to be wrong.)
/* This Program generates a file with a pseudo-random number of st_record_t structures. The file is passed by command line arguments. The program must by executed, in UNIX, this way: ./file_gen -path <path> */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "types.h"
#define MSG_INVALID_INPUT "Your input was not valid"
#define CMD_FLAG_PATH_POSITION 1
#define CMD_ARG_PATH_POSITION 2
#define CMD_FLAG_PATH "-path"
#define SDM_MAX 10000.0
status_t validate_arguments (int argc, char * argv []);
int main (int argc, char * argv [])
{
FILE * fi;
size_t i;
st_record_t aux_struct, aux2_struct;
int size;
if ((validate_arguments(argc, argv))!= OK)
{
fprintf(stderr, "%s\n", MSG_INVALID_INPUT);
return EXIT_FAILURE;
}
if((fi = fopen(argv[CMD_ARG_PATH_POSITION], "wb")) == NULL)
return EXIT_FAILURE;
srand(time(NULL));
for (i=0; i<(size=100); i++)
{
aux_struct.SDM = (((float)rand()/(float)(RAND_MAX)) * SDM_MAX); /*pseudo-random real number between 0 and SDM_MAX*/
(aux_struct.ID) = i;
(aux_struct.coordinates)->latitude.deg = rand()%180;
(aux_struct.coordinates)->latitude.min = rand()%60;
(aux_struct.coordinates)->latitude.sec = rand()%60;
(aux_struct.coordinates)->longitude.deg = rand()%180;
(aux_struct.coordinates)->longitude.min = rand()%60;
(aux_struct.coordinates)->longitude.sec = rand()%60;
if((fwrite (&aux_struct, sizeof(st_record_t), 1, fi))!=1)
return ERROR_WRITING_FILE;
}
if(fclose(fi) == EOF)
return EXIT_FAILURE
return EXIT_SUCCESS;
}
The problem is with the (aux_struct.coordinates)->latitude.deg = rand()%180 lines. If instead of using a random number I select one, this won't happen
The st_record_t struct is defined this way:
typedef struct {
unsigned char deg, min, sec;
}angle_t;
typedef struct {
angle_t latitude, longitude;
}st_coord_t;
typedef struct {
float SDM;
size_t ID;
st_coord_t * coordinates;
}st_record_t;
The segmentation fault has nothing to do with random number, it's because you never allocate memory for aux_struct.coordinates.
To fix the problem, use something like:
aux_struct.coordinates = malloc(sizeof(st_coord_t));
Remember to free the memory when it's not used any more.
In addition to the issue of the missing initialization of the "coordinates" member, it should be pointed out that the fwrite() will not do what you want. It will just write the contents of the st_record_t. The value of the pointer "coordinates" has no meaning outside the process that is doing the writing and the data in the st_coord_t structure it points to will not get written at all.
You might want to look at something like hdf5 to write complex binary data structures to file in a portable way.
You have
typedef struct {
float SDM;
size_t ID;
st_coord_t * coordinates;
}st_record_t;
As you can see,coordinates is a pointer of type st_coord_t. You need to allocate memory for it using malloc:
aux_struct.coordinates=malloc(sizeof(st_coord_t));
And you need to free the allocated memory after its use using:
free(aux_struct.coordinates);
Note that you must allocate memory for coordinates in aux2_struct if you want to use it and later free it after its use.
I'm trying to implement a stack using array pointer. When the stack is full, it expands twice of its original size. When the number of elements stored in the stack is half size of the stack, it shrinks in half. Push works fine. The problem is pop. When I put testSize in pop, the program crashes (See balded lines). Can anyone help me find me to fix it?
#include <stdio.h>
#include "stack.h"
#include <stdlib.h>
double* initialize(int* top)
{
*top=0;
return (double*)malloc(sizeof(double)*2);
}
// add a new value to the top of the stack (if not full)
void push(double* stack, int* top, const double new_value, int *stack_size)
{
*(stack+*top)=new_value;
++*top;
testSize(stack,stack_size,top);
}
// remove (and return) the value at the top of the stack (if not empty)
double pop(double* stack, int* top,int* stack_size)
{
**//testSize(stack,stack_size,top);**
if(*top)
{
int temp=--*top;
double result= *(stack+temp);
**//testSize(stack,stack_size,top);**
return result;
}
printf("%d top \n",*top);
return 0;
}
void testSize(double *stack, int *stack_size, int * top) //size operation
{
if(*top==*stack_size) //see if it is full
{
stack=(double*)realloc(stack,(*stack_size)*sizeof(double)*2); //expand size reallocate memory
*stack_size=*stack_size*2;
}else if(*top<*stack_size/2)
{
//shrink
}
}
#include <stdlib.h>
#include <stdio.h>
#include "stack.h"
int main(int args, char* argv[])
{
double* my_stack = NULL;
int my_top = 0;
int stack_size=2; //initial dynamic array size
my_stack=initialize(&my_top); //initial size of 2
int p;
for(p=0;p<10;++p)
push(my_stack,&my_top,p+0.1,&stack_size);
pop(my_stack,&my_top,stack_size);
printf("%d elements total \nDynamic current stack size %d \n",my_top,stack_size); //summary
//print stack
int i;
for(i=my_top-1; i>=0; --i)
{
printf("%f \n", *(my_stack+i));
}
free(my_stack);
return 0;
}
This line:
pop(my_stack,&my_top,stack_size);
should be
pop(my_stack,&my_top,&stack_size); /* take address of stack_size with '&' */
I suggest you compile with the -Wall option and look for warnings, then eliminate them. This will not only improve your coding style but help you find this sort of thing quickly.
Your pop() function takes an int* as the 3rd parameter, but you're passing an int in the following line:
pop(my_stack, &my_top, stack_size);
Should be:
pop(my_stack, &my_top, &stack_size);
So in testSize() when you try to de-reference this non-pointer the program crashes.