Struct Array Bug - c

Hi All,
from the above image.
I am able to compile, but the program crashes at runtime.
Please advise me what could be the resolution to solve this?
Thank you
// structArray.h:
#ifndef __STRUCTARRAY_H_
#define __STRUCTARRAY_H_
typedef struct _vector{
int* str;
int maskSize;
// etc...
}__attribute__((__packed__)) _vector_t;
#endif /* _STRUCTARRAY_H_ */
**// do_structArray.c**
#include "structArray.h"
extern struct _vector_t t;
void do_structArray (void) {
int plaintext[2] = {0x05, 0x08};
_vector_t t[] = {
{plaintext, sizeof(plaintext)},
//{},
};
printf("Content: \n%x \n", t[1].str[1]);
}
// main : just calling do_structArray
#include <stdio.h>
#include <stdlib.h>
#include "structArray.h"
extern struct _vector_t t;
int main(int argc, char *argv[]) {
do_structArray();
system("PAUSE");
return 0;
}

You are accessing t[1] but only have one item in t. Try printf("Content: \n%x \n", t[0].str[1]).

Array indices begin from 0 in C. You're accessing an array element past the end of the array. Change the index to 0:
printf("Content: \n%x \n", t[0].str[0]);

Related

ADT (using a header file, source file and main file) in C

I am trying to create a simple ADT using a structure that takes 2 dates. Then returns an age. It must use a Header file, a source file for the Header file, and a main file.
This is what I have it runs and nothing happens. Can someone tell me what i am doing wrong?
age.h
#ifndef AGE_H_
#define AGE_H_
typedef struct getage * Age;
#define MAX 5
Age get_Age(int birthYear, int yearNow);
void age_Destroy(Age a);
#endif
age.c
#include <stdio.h>
#include "age.h"
struct getage {
int birthYear;
int yearNow;
};
Age a[1];
Age get_Age(int birthYear, int yearNow){
int giveAge = 0;
giveAge = a[0]->yearNow - a[0]->birthYear;
printf("%d",giveAge);
return 0;
}
void age_Destroy(Age a){
free(a);
}
main.c
#include <windows.h>
#include <stdio.h>
#include "age.h"
void age_print(Age a);
void age_print(Age a){
printf("%d\n", &a);
}
int main() {
Age a;
get_Age(1986, 2020);
age_print(a);
printf("%d\n", &a);
system("pause");
//age_Destroy(a);
}
What are wrong:
In the function get_Age:
Instead of allocating structures, a[0] (global variable, initialized to NULL) is dereferenced.
0 (converted to NULL) is returned instead of returning an age.
In the function age_Destroy:
free() is used without declaration nor including proper header.
In the function age_print:
Data having wrong type is passed to printf(): %d requests int but Age* is passed.
In the function main:
The return value of get_Age is dropped.
Data having wrong type is passed to printf(): %d requests int but Age* is passed.
Fixed code that won't cause Segmentation Fault nor undefined behavior:
age.h (not changed)
#ifndef AGE_H_
#define AGE_H_
typedef struct getage * Age;
#define MAX 5
Age get_Age(int birthYear, int yearNow);
void age_Destroy(Age a);
#endif
age.c
#include <stdio.h>
#include <stdlib.h> // for malloc() and free()
#include "age.h"
struct getage {
int birthYear;
int yearNow;
};
Age get_Age(int birthYear, int yearNow){
Age a = malloc(sizeof(*a)); // allocate a structure
if (a == NULL) { perror("malloc"); exit(1); }
a->yearNow = yearNow; // assign data
a->birthYear = birthYear;
int giveAge = 0;
giveAge = a->yearNow - a->birthYear;
printf("%d",giveAge);
return a; // return pointer to the allocated structure
}
void age_Destroy(Age a){
free(a);
}
main.c
#include <stdlib.h> // more portable header for system()
#include <stdio.h>
#include "age.h"
void age_print(Age a);
void age_print(Age a){
printf("%p\n", (void*)a); // use valid combination of format and data
}
int main() {
Age a;
a = get_Age(1986, 2020); // assign the return value
age_print(a);
printf("%p\n", (void*)a); // use valid combination of format and data
system("pause");
age_Destroy(a); // enable freeing
}
(Some behavior may look weird, but I believe this is valid because not desired behavior is described.)

How do I print elements of structures contained in an array

I have created an array of structure as a global variable. I initialised the array in a function and I could print out the elements of the structure from there. My problem is that I can't print out values of the array in another function( main() in my case) other than the one I used to initialise the array. Please how can I print those values? Thank you.
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
typedef struct s{
char *value;
} S;
S list[2];
void function( ){
char val1[] = "val1";
char val2[] = "val2";
S v1 = {val1};
S v2 = {val2};
list[0] = v1;
list[1] = v2;
printf("%s\n", list[1].value); //prints val2
}
int main(int argc, char** argv) {
function();
printf("%s", list[1].value); //prints nonsense
return 0;
}
What I have tried :
I modified function() to take list as an argument( function (list)) and declared list in main() instead. It didn't work.
I modified function to return list (S* function()), it didn't work.
I used an array of integers ( instead of structure i.e. int list[2], declared it as a global variable and initialised it in function()) and everything worked fine, suggesting that the problem is from how I am accessing structure, but I just can't figure it out.
I searched the internet, but couldn't get a similar problem.
In your function function you assign an address of a local variable to your structure. After returning from function this address is no longer valid. You could either make it static or allocated it dynamically.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct s
{
char *value;
} S;
S list[2];
void function( )
{
char val1[] = "val1";
char val2[] = "val2";
//Note that you are creating a copy of "val1" here which can be avoided by changing it to char *val1 = "val1";
list[0].value = malloc(strlen(val1)+1); //allocate space for val1 + NUL-terminator
strcpy(list[0].value, val1); //copy string
list[1].value = malloc(strlen(val2)+1);
strcpy(list[1].value, val2);
//You could also use the function strdup which allocates memory and duplicates the string
//list[0].value = strdup(val1);
printf("%s\n", list[1].value); //prints val2
}
int main(int argc, char** argv)
{
function();
printf("%s", list[1].value);
free(list[0].value); //Don't forget to free.
free(list[1].value);
return 0;
}

Pointers to structures, fields changing values inexplicably

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.

Sample program using Function Pointer and structures.

I created a structure and wanted to assign the values to a Function Pointer of another structure. The sample code I wrote is like below. Please see what else I've missed.
#include <stdio.h>
#include <string.h>
struct PClass{
void *Funt;
}gpclass;
struct StrFu stringfunc;
struct StrFu{
int a ;
char c;
};
Initialise(){
}
main()
{
stringfunc.a = 5;
stringfunc.c = 'd';
gpclass.Funt = malloc(sizeof(struct StrFu));
gpclass.Funt = &stringfunc;
memcpy(gpclass.Funt,&stringfunc,sizeof(struct StrFu));
printf("%u %u",gpclass.Funt->a,gpclass.Funt->c);
}
There are several problems:
A function pointer is not the same as void *, in fact you cannot rely on being able to convert between them.
You shouldn't cast the return value of malloc() in C.
You shouldn't call malloc(), then overwrite the returned pointer.
You don't need to use malloc() to store a single pointer, just use a pointer.
You shouldn't use memcpy() to copy structures, just use assignment.
There are two valid main() prototypes: int main(void) and int main(int argc, char *argv[]), and you're not using either.
there is lots of problem in your code , I try to correct it ,hope it will help
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct PClass{
void *Funt;
}gpclass;
struct StrFu{
int a ;
char c;
};
struct StrFu stringfunc;
int main()
{
stringfunc.a = 5;
stringfunc.c = 'd';
gpclass.Funt = malloc(sizeof(struct StrFu));
gpclass.Funt = &stringfunc;
memcpy(gpclass.Funt,&stringfunc,sizeof(struct StrFu));
printf("%d %c",((struct StrFu*)gpclass.Funt)->a,((struct StrFu*)gpclass.Funt)->c);
return 0;
}
it outputs
5 d

Error while executing: Segmentation fault

I'm a beginner in C language. After reading the initial chapters of Ritchie's book, I wrote a program to generate random numbers and alphabets.
The program compiles fine with gcc. However on running it, it gives an error "Segmentation fault", which is incomprehensible to my limited knowledge. I'd be glad to understand what I've written wrong.
#include <stdio.h>
#include <stdlib.h>
#include "conio.h"
#include <time.h>
long int genrandom(int,int);
void randAlph(void);
char letterize(int);
int main (void) {
// char full[9];
// char part_non[4];
srand(time(0));
int i;
for (i=0;i<50;++i) {
randAlph();
};
}
long int genrandom(int mino,int maxo) {
int val=mino+rand()/(RAND_MAX/(maxo-mino)+1);
return val;
}
void randAlph (){
int val;
char text;
val=genrandom(0,26);
// return val;
text=letterize(val);
printf("%s ,",text);
}
char letterize(int num) {
char letter='A'+num;
return letter;
}
printf("%s ,",text); is wrong - it says that text is a nul-terminated array of chars. Use
printf("%c ,", text);
instead to print your single char.
#include <stdio.h>
#include <stdlib.h>
#include "conio.h"
#include <time.h>
int genrandom(int,int);
void randAlph(void);
char letterize(int);
int main (void) {
// char full[9];
// char part_non[4];
srand(time(0));
int i;
for (i=0;i<50;++i) {
randAlph();
};
}
int genrandom(int mino,int maxo) {//changed function return type to int
int val=mino+rand()/(RAND_MAX/(maxo-mino)+1); //Be careful when you are using '/' operator with integers
return val; //returning int here why set return type to long int?
}
void randAlph (){
int val;
char text;
val=genrandom(0,26);
// return val;
text=letterize(val);
printf("%c ,",text);//Replace %s with %c
}
char letterize(int num) { //No bound checking on num eh?
char letter='A'+num;
return letter;
}
That's all I had to say. :)
Why use %s when text is char. You dont need a string type in the function. Just a char would do. Change in the function : void randAlph ()
printf("%s ,",text);
to
printf("%c ,", text);

Resources