gcc segmentation fault due to a pointer variable that changed itself - c

Let's consider follwing code.
message_word.h
struct array_int64{
int size;
long* value;
};
struct array_int64* array_int64_create(int size);
int array_int64_get(void* value, const struct array_int64* array, int index);
int array_int64_set(struct array_int64* array, long value, int index);
void array_int64_free(struct array_int64* array);
struct hello_message{
struct array_int64* test;
};
struct hello_message* hello_message_create();
void hello_message_free(struct hello_message* msg);
message_word.c
#include <stdlib.h>
#include <string.h>
#include "word_message.h"
struct array_int64* array_int64_create(int size){
struct array_int64* new_array = (struct array_int64*)malloc(sizeof(struct array_int64));
new_array->size = size;
new_array->value = (long*)malloc(sizeof(long) * (new_array->size));
return new_array;
}
int array_int64_get(void* value, const struct array_int64* array, int index){
long* vvalue = (long*)value;
if(index >= array->size)
return -1;
*vvalue = (array->value)[index];
return 0;
}
int array_int64_set(struct array_int64* array, long value, int index){
if(index >= array->size)
return -1;
array->value[index] = value;
return 0;
}
void array_int64_free(struct array_int64* array){
if(array != NULL && array->value != NULL)
free(array->value);
if(array != NULL)
free(array);
}
struct hello_message* hello_message_create(){
struct hello_message* new_msg = (struct hello_message*)malloc(sizeof(struct hello_message));
new_msg->test = array_int64_create(5);
return new_msg;
}
void hello_message_free(struct hello_message* msg){
if(msg == NULL) return;
array_int64_free(msg->test);
free(msg);
}
main.c
#include "word_message.h"
#include <stdio.h>
//struct hello_message* msg = NULL;
int main(void)
{
struct hello_message* msg = hello_message_create();
//msg = hello_message_create();
array_int64_set(msg->test, 10, 0);
int number;
array_int64_get(&number, msg->test, 0);
printf("value is: %d\n", number);
array_int64_get(&number, msg->test, 0);
printf("value is: %d\n", number);
hello_message_free(msg);
return 0;
}
When I compile and run this code with gcc-9.3.0 or gcc-7.5.0 on Ubuntu the msg reference address changes itself when array_int64_get is executed. However, if you make msg a global variable like in the comment, it does not change.When I compile and run this code on Ubuntu 18, gcc-7.5.0 on a Raspberry Pi (ARM), everything works fine. It also works fine on windows. So is this a bug in gcc?
This is the result of running on ubuntu18(x86)+gcc-9.3.0
running on ubuntu18
This is the result of running it on a Raspberry Pi
run on raspberry pi

int array_int64_get(void* value, const struct array_int64* array, int index){
long* vvalue = (long*)value;
...
}
int main() {
int number;
array_int64_get(&number, msg->test, 0);
}
You are passing an int with a pointer and then reading it as long. That's invalid. If you want it long, be it long.
Use longs everywhere, and if your functions wants a long make it take a long.
int array_int64_get(long *vvalue, const struct array_int64* array, int index){
...
}
int main() {
int number;
array_int64_get(&number, ...); // compiler warning!
long correctnumber;
array_int64_get(&correctnumber, ...); // all fine!
}
Conceptually, your code is odd. long is not 64-bit long, it's at least 32-bits long. It can have 32-bits, 64-bits, 1000-bits. For 64-bit, use uint64_t or int64_t from #include <stdint.h>. See https://en.cppreference.com/w/c/types/integer .
free(NULL) is totally fine - no need to check for it.
Do I cast the result of malloc?

Related

gcc.exe warning cast from pointer to integer of different size [-Wpointer-to-int-cast]

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef void SeqList;
typedef void SeqListNode;
typedef unsigned int TSeqListNode;
typedef unsigned int TSeqListNode;
typedef struct _tag_SeqList
{
int capacity;
int length;
TSeqListNode *node;
}TSeqList;
SeqList * SeqList_Create(int capacity)
{
TSeqList *ret = NULL;
if(capacity>=0)
{
ret = (TSeqList *)malloc(sizeof(TSeqList) + sizeof(TSeqListNode)*capacity);
}
if(ret == NULL)
{
printf("malloc fail.\n");
exit(-1);
}
ret->capacity = capacity;
ret->length = 0;
ret->node = (TSeqListNode*)(ret+1);
return ret;
}
int SeqList_Insert(SeqList *list, SeqListNode *node, int pos)
{
TSeqList *sList = (TSeqList*)list;
int ret = (sList != NULL);
int i = 0;
ret = ret && (sList->length+1 <= sList->capacity);
ret = ret && (0 <= pos);
if(ret)
{
if(pos >= sList->length)
{
pos = sList->length;
}
for(i=sList->length; i > pos; i--)
{
sList->node[i] = sList->node[i-1];
}
sList->node[i] = (TSeqListNode)node;
sList->length++;
}
return ret;
}
int main()
{
system("pause");
return 0;
}
D:\mingw64\bin\gcc.exe -g D:\Cpp\DSA\test001.c -o D:\Cpp\test001.exe
D:\Cpp\test001.c: In function 'SeqList_Insert':
D:\Cpp\test001.c:56:26: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
sList->node[i] = (TSeqListNode)node;
^
What you are trying to do is already part of the ISO/IEC 9899:1999 C standard. It's called flexible array member. So no need for inventing your own code - just use what is already available.
Also notice that capacity and length are variables that can't be negative. So you should use an unsigned type. The common used type would be size_t.
So your code should be:
typedef struct _tag_SeqList
{
size_t capacity;
size_t length;
TSeqListNode node[]; // Flexible array member
} TSeqList;
Now you can simply do:
ret = malloc(sizeof(TSeqList) + sizeof(TSeqListNode)*capacity);
\--------------/ \----------------------------/
Memory for the Memory for the 'node' array
struct, i.e for with 'capacity' elements
capacity and
length
to allocate (no need for checking the value of capacity as it can't be negative).
And just use node as a normal array.
All the need for casts are gone.
Earlier versions of the C standard (C90) probably do necessitate casting. I think a placeholder data (int *)(array + 1) is entirely appropriate in some situations, assuming alignment is respected. Note that you might also make this design decision to comply with MISRA C 2012 Rule 18.7. I have eliminated the obfuscating typedefs and renamed parts of it to reflect what it actually does more clearly. A cast to void * is basically turning off type-checking, (through a typedef or not,) and should be avoided where possible.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct IntArray {
size_t capacity;
size_t length;
int *node;
};
/** #throws[malloc] */
static struct IntArray *IntArray_Create(const size_t capacity)
{
struct IntArray *ret = NULL;
ret = malloc(sizeof *ret + sizeof *ret->node * capacity);
if(ret == NULL) return 0; /* Let the caller decide what to do. */
ret->capacity = capacity;
ret->length = 0;
ret->node = (int *)(ret+1);
return ret;
}
/** Returns false if the `array` is full or null. Clips `pos` to `array`. */
static int IntArray_Insert(struct IntArray *array, const int node, size_t pos)
{
if(!array || array->length >= array->capacity) return 0;
if(pos >= array->length) pos = array->length;
/* Replaced looping over the array for performance. */
memmove(array->node + pos + 1, array->node + pos, array->length - pos);
array->length++;
array->node[pos] = node;
return 1;
}
#include <assert.h>
int main(void)
{
struct IntArray *a;
if(!(a = IntArray_Create(3))) { perror("fail"); return EXIT_FAILURE; };
assert(IntArray_Insert(a, 1, 42));
assert(IntArray_Insert(a, 3, 1));
assert(IntArray_Insert(a, 2, 1));
assert(!IntArray_Insert(a, 2, 1));
free(a);
return 0;
}
If you are targeting C99 or later, the flexible array member may be useful for this exact reason. If this is part of a macro, the only typedef you really need is typedef int ArrayType;.

how to do dynamic allocation in boundless array

Well I am wanting to change the way my structures are written, currently I use array and I need to limit its use, but I wanted a way to create a dynamic array that is the size of the reading done, without always having to edit the array value.
Current Code:
struct sr_flag {
int value_flag;
};
struct er_time {
int value_time;
};
struct se_option {
struct sr_flag flag[50];
struct er_time time[50];
};
struct read_funcs
struct se_option *option;
void (*option_func) (void);
...
}
struct read_funcs func_;
struct read_funcs *func;
int sr_flags(int i, int fg, int val) {
if(i < 0)
return 0;
return func->option[i].flag[fg].value_flag = val;
}
void option_func(void) {
struct se_option fnc;
fnc.option = malloc(500 * sizeof(*(fnc.option)));
}
void read_fnc() {
func = &func_;
func->option = NULL;
func->option_func = option_func;
}
I look for a way to remove the array amount [50] instead each time the sr_flags function is executed the limit is raised
Example: sr_flags function executed 1x array would be [1] if executed 2x would be [2]
I also think about doing the same with the option_func function
I tried using the following more unsuccessfully
struct se_option {
struct sr_flag *flag;
struct er_time time[50];
};
int sr_flags(int i, int fg, int val) {
if(i < 0)
return 0;
func->option[i].flag = malloc(1 * sizeof(*(func->option[i].flag)));
return func->option[i].flag[fg].value_flag = val;
}
int main () {
for(int i < 0; i < 10; i++)
sr_flags(i, 1, 30);
return 0;
}
I'm not 100% certain on what it is you want but I think you just want to call realloc and increase the size by the amount you provide. And that's very easy to do, as for the values you want with the arrays I'm not sure so I just used a placeholder value.
#include <stdio.h>
#include <stdlib.h>
struct sr_flag {
int value_flag;
};
struct er_time {
int value_time;
};
struct se_option {
struct sr_flag* flag;
struct er_time* time;
};
void allocateflags(struct se_option* options, int size, int val){
options->flag = realloc(options->flag, size*sizeof(struct sr_flag));
struct sr_flag* flag = options->flag+size-1;
flag->value_flag = val;
}
void allocatetime(struct se_option* options,int size, int val){
options->time = realloc(options->time, size*sizeof(struct er_time));
struct er_time* time = options->time+size-1;
time->value_time = val;
}
void displayflagvalues(struct se_option* options,int size){
for(int index = 0; index < size ; ++index){
printf("flag: %i\n",options->flag[index].value_flag);
}
}
void displaytimevalues(struct se_option* options, int size){
for(int index = 0; index < size ; ++index){
printf("time: %i\n",options->time[index].value_time);
}
}
int main(){
struct se_option options = {0};
for(int index = 0; index < 10; ++index){
allocateflags(&options, index,index);
allocatetime(&options, index,index);
}
displayflagvalues(&options, 10);
displaytimevalues(&options,10);
return 0;
}
The code creates an se_option structure wheren sr_flag and er_time pointers are null. Then there's two functions one allocateflags and the other allocatetime, both of which call realloc with the size you provide. When you call realloc, all previous memory is copied over to the new array. Also free is called automatically by realloc.
This step
struct sr_flag* flag = options->flag+size-1;
flag->value_flag = val;
struct er_time* time = options->time+size-1;
time->value_time = val;
Is slightly redundant but it was just to show the newest array can hold the value. If you understand pointer arithmetic, all its doing is incrementing the pointer to the last position then subtracting 1 struct size and setting that value. Basically setting the value of the final array in the pointer.

Segmentation fault on separate chaining hashtable

So i implemented a hashtable with separate chaining for a struct called Objective, so that i could perform some operations on said Objectives. Currently i have this:
Hashtable.h:
#ifndef HASHTABLE_H
#define HASHTABLE_H
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/*Using separate chaining to store the obejctives*/
typedef struct Objective{
char name [8000];
unsigned long id, duration, deps [9000];
int hasDeps;
}*pObjective;
typedef struct nodehash{ /*Node of list*/
pObjective obj;
struct nodehash*next;
}*link;
void Init(int M);
int search(unsigned long id);
void insert(pObjective o);
void delete(unsigned long id);
link insertBegin(link h, pObjective obj);
int searchList(link h, unsigned long id);
link removeList(link h, unsigned long id);
pObjective searchObj(unsigned long id);
pObjective searchObjAux(link h, unsigned long id);
#endif
Objectives.c:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "OBJECTIVES.h"
/*Checks if all inserted dependencies already exist*/
int existDeps(unsigned long dep[9000]){
int i, count = 0;
for(i = 0; i < 9000; i++){
if(search(dep[i]) != 0)
count++;
}
return count;
}
/ *Adds objective with dependencies*/
void addObj(unsigned long id, char name [8000], unsigned long duration,
unsigned long dep[9000]){
int i;
pObjective obj = malloc(sizeof(pObjective));
obj->id = id;
obj->duration = duration;
obj->hasDeps = 1;
strcpy(name, obj->name);
for(i = 0; i < 9000; i++){
obj->deps[i] = dep[i];
}
if(search(id) != 0)
printf("id already exists\n");
else if(existDeps(dep) != 0)
printf("no such task\n");
else
insert(obj);
free(obj);
}
/*Adds objective with no dependencies*/
void addNoDeps(unsigned long id, char name [8000], unsigned long
duration){
pObjective obj = malloc(sizeof(pObjective));
obj->id = id;
obj->duration = duration;
obj->hasDeps = 1;
strcpy(name, obj->name);
if(search(id) != 0)
printf("id already exists\n");
else
insert(obj);
free(obj);
}
/*Removes objective with no dependencies*/
void removeObj(unsigned long id){
int res = search(id);
pObjective obj = searchObj(id);
if(res == 0)
printf("no such task\n");
else if(obj->hasDeps == 1)
printf("task with dependencies\n");
else
delete(id);
}
Objectives.h:
#ifndef OBJECTIVES_H
#define OBJECTIVES_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "HASHTABLE.h"
/*Functions to work with objectives*/
int existDeps(unsigned long dep[9000]);
void addObj(unsigned long id, char name [8000], unsigned long duration,
unsigned long dep[9000]);
void addNoDeps(unsigned long id, char name [8000], unsigned long
duration);
void removeObj(unsigned long id);
#endif
Hashtable.c:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "HASHTABLE.h"
#define hash(A,B) (A%B) /*Hash function*/
static link *heads;
static int M;
/*Initiates hashtable with size m*/
void Init(int m){
int i;
M = m;
heads = (link*)malloc(M*sizeof(link));
for(i = 0; i < M; i++)
heads[i] = NULL;
}
/*Searches objective with said id*/
int search(unsigned long id){
int i = hash(id, M);
return searchList(heads[i], id);
}
/*Inserts objective into hashtable*/
void insert(pObjective o){
int i = hash(o->id, M);
heads[i] = insertBegin(heads[i], o);
}
/*Deletes objective using it's id*/
void delete(unsigned long id){
int i = hash(id, M);
heads[i] = removeList(heads[i], id);
}
/*Returns objective with said id*/
pObjective searchObj(unsigned long id){
int i = hash(id, M);
return searchObjAux(heads[i], id);
}
/*Inserts objective into list*/
link insertBegin(link h, pObjective obj){
link new = (link)malloc(sizeof(struct nodehash));
new->obj = obj;
new->next = h;
return new;
}
/*Searches objective by id in a list*/
int searchList(link h, unsigned long id){
link t;
int count = 0;
for(t = h; t != NULL; t = t->next){
if(t->obj->id == id)
count++;
}
return count++;
}
/*Removes objective from list*/
link removeList(link h, unsigned long id){
link t, x, z;
for(t = h; t != NULL; t = t->next){
if(t->next->obj->id == id)
x = t;
}
z = x->next;
x->next = z->next;
free(z);
return h;
}
/*Returns objetive from said id from list*/
pObjective searchObjAux(link h, unsigned long id){
link t, x;
for(t = h; t != NULL; t = t->next){
if(t->obj->id == id)
x = t;
}
return x->obj;
}
I'm quick testing the funcions addObj (adds an objective with dependencies) and addNoDeps (adds an objective with no dependencies) on my main:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "OBJECTIVES.h"
int main(){
unsigned long array [1] = {3};
Init(11);
addNoDeps(1, "tarefa1", 20);
addObj(2, "tarefa2", 20, array);
return 0;
}
But i keep getting segmentation fault(core dumped) and i can't figure out why. Is my implementation wrong? Are the functions wrong? I can't get to the problem, can someone help me?
I can't run your code right now so I can't analyze the core dump, but I believe what is happening is that you are trying to access memory that has already been freed. At the end of addNoDeps, you free the pObjective after putting it into the list. Then, when you addObj after, you search the list and check to make sure that the links object associated with it is not null. Specifically this code:
for(t = h; t != NULL; t = t->next){
if(t->obj->id == id)
count++;
You only check to see that the t (links pointer) is not null, but since you freed the previous object, the t->obj pointer is not pointing to initialized memroy. Therefore trying to access it via t->obj->id is accessing uninitialized memory. If you remove the free(obj) at the end of your addNoDeps and addObj functions you should be fine. You may also want to add checks to make sure that t->obj is not null as well. In general segmentation faults are caused by accessing uninitialized memory, so when debugging check for accessing pointers after a free, double frees, and other things. Also learning to use GDB can help a lot in these situations.

Reallocating pointers to a struct

I'm having an issue understanding this, my code below:
#include <stdio.h>
#include <stdlib.h>
typedef struct mee test;
typedef struct aa fill;
struct aa {
int c;
fill *point;
};
struct mee {
char name;
fill **a;
int b;
};
static fill **store;
static fill *talloc(int tsize);
static int mem;
static int ptr;
static fill *talloc(int tsize)
{ int temp;
temp = ptr;
ptr++;
mem = mem + tsize;
store = realloc(store, mem*sizeof(fill));
store[temp] = malloc(sizeof(fill));
return store[temp];
}
int main() {
test *t;
t = malloc(sizeof(test));
t->a = malloc(sizeof(fill *)*10);
printf("where\n");
for(int i= 0; i < 10; i++) {
t->a[i] = talloc(1);
}
printf("%d\n", store[9]->c); //Problem here
return 0;
}
excuse the terrible names, just some test code for a larger project. This code compiles and runs fine. if I set the code:
printf("%d\n", store[9]->c);
store[0-7] I get 0 as the output, though why does 8-9 give me some gibberish negative number? I'm assuming its a loss it the pointer somewhere.
How can I correct this?
For some background, this is to store pointers to struct in a array so I can free them a lot easier later.

Vector in C crashing

I tried to write a vector in c using memory operations.Compiler shows no errors but if I try to print an element from the vector it simply crashes. And whenever I try to print destination variable (printf((int) destination)) the program crashes again.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef struct{
void* elemList;
int elemSize;
int maxSize;
int curSize;
}myvector;
void initVec(myvector * vec, int typeSize){
vec->curSize = 0;
vec->maxSize = 10;
vec->elemSize =typeSize;
vec->elemList = malloc(10*sizeof(typeSize));
}
void add(myvector * vec, void* elem){
if(vec->curSize >= vec->maxSize){
vec->elemList = realloc(vec->elemList, vec->maxSize*2);
}
memcpy(&vec->elemList[vec->curSize],elem,vec->elemSize);
}
void get(myvector * vec, int index, void* destination){
if(index > vec->curSize || index < 0){
printf("Invalid Index");
return;
}
destination = malloc(vec->elemSize);
memcpy(destination,&vec->elemList[index], vec->elemSize);
}
int main()
{
myvector newVec;
initVec(&newVec,sizeof(int));
int a = 5;
add(&newVec,&a);
int* b;
get(&newVec,0,b);
printf(*b);//this is where the program crashes
return 0;
}
Basically the pointer in the get is not handled correctly. It's being passed by value so a copy of the pointer is made, the copy is modified (memory allocation is done for this copy), but the original pointer once you quit the get method is not pointing to a valid memory. You have to pass the address of the pointer. Following is a modified code (note the double ** in the destination in the get method). Basically I pass the address of the "destination" pointer instead of the pointer itself. Additionally I fixed the line sizeof(typeSize) .. it should be typeSize only since you are already calling the initVec method with sizeof operator.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef struct{
void* elemList;
int elemSize;
int maxSize;
int curSize;
}myvector;
void initVec(myvector * vec, int typeSize){
vec->curSize = 0;
vec->maxSize = 10;
vec->elemSize = typeSize;
vec->elemList = malloc(vec->maxSize*typeSize);
}
void add(myvector * vec, void* elem){
if(vec->curSize >= vec->maxSize)
{
vec->elemList = realloc(vec->elemList, vec->maxSize*2);
}
memcpy(&vec->elemList[vec->curSize], elem, vec->elemSize);
vec->curSize++;
}
void get(myvector * vec, int index, void** destination){
if(index > vec->curSize || index < 0)
{
printf("Invalid Index");
return;
}
*destination = malloc(vec->elemSize);
memcpy(*destination, &vec->elemList[index], vec->elemSize);
}
int main()
{
myvector newVec;
initVec(&newVec,sizeof(int));
int a = 5;
add(&newVec,&a);
int* b;
get(&newVec, 0, &b);
printf("value of b is %d\n", *b); // This works correctly now
return 0;
}
A couple of issues with the code :
vec->elemList = malloc(10*sizeof(typeSize)); should be vec->elemList = malloc(10*typeSize);
If you would like get to create a pointer to int I would recommend either defining it like int* get(myvector * vec, int index) and return a newly allocated pointer to int or in the main function use :
int b;
get(&newVec, 0, &b);
the latter will also avoid memory leaks.
printf(*b); is wrong as you are passing an int and it expects a char* use either printf("%d", b); if b is an int or printf("%d", b);if b is aint`
you are using malloc a lot but no free. In this particular program you don't get memory leaks as the OS will reclaim all memory when main returns. But think early about a function to clear your vector and.
*b shouldn't be a valid pointer to string, so it will cause crash.
Try printing it by printf("%d",*b);
To make it better, you should free the buffer that are allocated by malloc.
UPDATE
The get function is wrong since it throws away the buffer allocated to destination
get function and main function should be like this:
void get(myvector * vec, int index, void** destination){
if(index > vec->curSize || index < 0){
printf("Invalid Index");
return;
}
*destination = malloc(vec->elemSize);
memcpy(*destination,&vec->elemList[index], vec->elemSize);
}
int main()
{
myvector newVec;
initVec(&newVec,sizeof(int));
int a = 5;
add(&newVec,&a);
int* b;
get(&newVec,0,&b);
printf("%d",*b);//this is where the program crashes
return 0;
}
But this still gives me Segmentation Fault. I'm working on.
UPDATE 2
You should think about the size of each elements.
You also forget the size information in add function.
This code should work if we don't care about memory leak.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef struct{
void* elemList;
int elemSize;
int maxSize;
int curSize;
}myvector;
void initVec(myvector * vec, int typeSize){
vec->curSize = 0;
vec->maxSize = 10;
vec->elemSize =typeSize;
vec->elemList = malloc(vec->maxSize*vec->elemSize);
}
void add(myvector * vec, void* elem){
if(vec->curSize >= vec->maxSize){
vec->elemList = realloc(vec->elemList, vec->elemSize * vec->maxSize*2);
vec->maxSize *= 2;
}
memcpy(vec->elemList + vec->curSize * vec->elemSize,elem,vec->elemSize);
vec->curSize++;
}
void get(myvector * vec, int index, void** destination){
if(index >= vec->curSize || index < 0){
printf("Invalid Index");
return;
}
*destination = malloc(vec->elemSize);
memcpy(*destination,vec->elemList + index * vec->elemSize, vec->elemSize);
}
int main()
{
myvector newVec;
initVec(&newVec,sizeof(int));
int a = 5;
add(&newVec,&a);
int* b;
get(&newVec,0,(void**)&b);
printf("%d",*b);
return 0;
}

Resources