Segmentation fault using char pointers in C [closed] - c

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 8 years ago.
Improve this question
With my current implementation of code, I'm getting a segmentation fault that I think is caused by trying to store several char* in another char*. However, I don't know a way around this being fairly new to C. I'm in a GLUE Unix environment. The code compiles but does not fully execute.
Here's my method that I think is causing the issue.
int totalLogins = 0, selectedLogins = 0,dateIn[3], timeIn[3], dateOut[3], timeOut[3];
int latest = 0,earliest=30,loggedIn = 0, firstTime[7][3],firstDate[7][3],i;
char* user[12], firstUser[7][12];
bool first = true;
void checkAndSetEarliest(int day)
{
first = true;
for(i = 0; i < 3 && first; i++)
{
first = (timeIn[i]<firstTime[day][i]);
}
if(first)
{
for(i = 0; i < 3; i++)
{
firstTime[day][i] = timeIn[i];
firstDate[day][i] = dateIn[i];
}
printf("user = %s\n",user);
firstUser[day] = user;
}
}
timeIn[],firstTime[][],firstDate[][], and dateIn[] are all ints
firstUser[] and user[] are char*
I'm trying to edit the contents of firstUser with the value of user.

First, the way you are using user[] in printf, it is suppose to be a char array, not an array of pointer to char (what you have declared).
Secondly, firstuser is a 2d arrray and you are using it as a 1d array.

You really need to show the definition of the variables this function uses. Fair chance that last line should be changed to:
strcpy( FirstUser[day], user );

Related

Malloc in array gives Segmentation fault [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
In my attempt to understand malloc and structs I have come across an error I do not understand
#include <stdio.h>
#include <stdlib.h>
typedef struct match
{
int round;
} match;
void foo(match *matches) {
for(int i = 0; i < 10; i++) {
matches = (match *) realloc(matches, i + 1);
matches[i].round = i + 1;
}
}
int main()
{
match *matches;
matches = (match *) malloc(0);
foo(matches);
free(matches);
return(0);
}
So in my attempt to fill this array of matches dynamicaly it fails
Your foo function is very flawed. First, the parameter passes a copy of the matches pointer, so when you realloc, that updates the foo matches pointer, but not the matches pointer in main. This may cause problems with the free in main. You need to change the parameter to foo to be a double pointer: void foo(match **matches). Then to realloc, *matches = realloc(...
Next, the second parameter to realloc is a size. But i + 1 isn't going to be big enough for a full copy of the match struct. You probably meant to do something like sizeof(struct match) * (i + 1).
I addition to above answer. Good Explanation...
Please check the error from realloc as well before using the memory,
Modified the program
void foo(match **matches) {
for(int i = 0; i < 10; i++) {
*matches = realloc(*matches, (i+1) * sizeof(match));
...
}
}
int main()
{
...
foo(&matches);
...
}

Some data disapears from pointer when calling a function [closed]

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 6 years ago.
Improve this question
[EDIT] The main problem was that the fitness of my evolution returned the same value every time after changing some int into float values. The misterious point is that i restarted the computer and it surprisingly worked again.
I'm calling a function from my main, when i debug the code, the variables contain data, but in the header of the function, when i debug, my data is lost and the reference on memory is the same (i'm compiling with visual Studio 2013), this only happens in some of the variables (you can check which ones in the pictures below)
int main(){
float resultados[NUMCROMOSOMAS][CANTIDADMEDICIONES];
int in[CANTIDADMEDICIONES][NUMVAR];
char gramaticas[NUMCROMOSOMAS][LONGITUDCADENA];
int mejorValorIndividuo[100];
char variableNames[NUMVAR + 1];
float fitness[NUMCROMOSOMAS];
char mejorindividuo[LONGITUDCADENA];
float medicionesObtenidas[NUMCROMOSOMAS][CANTIDADMEDICIONES];
int i,j;
(Initializations, some of the relevant ones are)
for (i = 0; i < NUMCROMOSOMAS; i++)
fitness[i] = 0.0;
for (i = 0; i < CANTIDADMEDICIONES; i++)
in[i][0] = i;
Yeah, that was a bidimensional array using one column
And here is the main loop of my program
int curr = MAXINT;
i = 0;
while ( isNotGoodEnough(curr) ){
i++;
curr = generacion(poblacion, results, input, collectedData, gramaticas, mejorindividuo, variableNames, fitness);
}
return poblacion[0][0];
}
The header of my function is this:
int generacion(int poblacion[NUMCROMOSOMAS][SIZECROMOSOMAS],
float resultados[NUMCROMOSOMAS][CANTIDADMEDICIONES],
int in[CANTIDADMEDICIONES][NUMVAR],
float valoresEsperados[NUMCROMOSOMAS][CANTIDADMEDICIONES],
char gramaticas[NUMCROMOSOMAS][LONGITUDCADENA],
char * mejorIndividuo,
char variableNames[NUMVAR],
float fitness[NUMCROMOSOMAS]){
Here is the compiler before the calling
Here is the compiler right after the calling
What i'm doing wrong?
When you have an argument declaration like
int in[CANTIDADMEDICIONES][NUMVAR]
that's not really what the compiler uses, what it translates it to is
int (*in)[NUMVAR]
In other words in is a pointer and not an array.
What you're seeing in the debugger in the function is the pointer, but since the size of the data pointed to by the pointer is unknown the debugger can't show you the data directly. If you explicitly, in the debugger when in the function, check in[0] you will see that the data is correct.
In other words, it's not a problem with the code, it's how the debugger displays (or rather doesn't display) the data.

function call from struct array [closed]

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 have a struct array that has the format:
struct command functions[] = {
{"1", function1},
{"2", function2},
etc....
}
In a function run(char* function), I check if the parameter is equivalent to one of the strings stored in the struct array. If it is, I want to call the corresponding function. For example, if "1" is passed in, I call function1().
How would this be accomplished?
So far, I have
run(char* function) {
for (int i = 0; i < num_functions; i++) {
if(*function == functions[i]) {
return (*function)();
}
}
}
With the following errors:
error: invalid operands to binary == (have int and struct command)
error: called object *function is not a function
There are several issues with your code that seem to be causing an error, but unfortunately you haven't posted enough for me to completely fix them.
In the line if(*function == function[i]) you are using function[i] when you probably want to be using functions[i] (with an "s")
In the same line, you are comparing a char against a struct command. You probably want to access the member of the struct that contains the string shown in your first code snippet.
You are (presumably) comparing a single character against a string. You should do this using strcmp.
You are not calling the function, you're calling a char, which just won't work.
At a guess, I think you want something like this:
run(char* function_name) {
for (int i = 0; i < num_functions; i++) {
struct_command function = functions[i];
if(strcmp(function_name, function.name) == 0) {
return function.exec();
}
}
}
This assumes that the members in your struct command are named name and exec.

segmentation fault while accessing an array element's [closed]

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
here is my problem, I malloc my array like that:
e->map = malloc(sizeof(int *) * e->map_y);
i = -1;
while (++i < e->map_x)
e->map[i] = malloc(sizeof(int) * e->map_x);
where e->map_y = 14 and e->map_x = 10
The problem is I can't access (I have a segfault) elements after e->map[10][0] (included)
I tough about I invert x and y but it doesn't seem to be the case here.
I can post my entire code if necessary, thx
hi, I added the entire project on github for more details: https://github.com/42-hbock/fdf
this part of the code is in src/default_reading.c, the malloc is in the function char *default_reading(char *file, t_env *e) and I have the segmentation fault while accessing in void create_int_map(char *cmap, t_env *e)
Should be:
e->map = malloc(sizeof(int *) * e->map_y);
i = -1;
while (++i < e->map_y)
e->map[i] = malloc(sizeof(int) * e->map_x);
The change is having the while look at e->map_y instead of e->map_x. The rest of the code is the same.

C - Segmentation fault on for loop using pointers & function [closed]

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 8 years ago.
Improve this question
I've got some trouble about a C function.
This is the function:
int* CalcMeanPower(int Media[], int** MeanPowerArray, int righe, int colonne)
{
int i=0, k=0;
int ArrayPower[] = {0, 0, 0, 0};
for (i=0; i<righe; i++)
{
for (k=0; k<colonne; k++)
{
ArrayPower[k] = ArrayPower[k] + MeanPowerArray[i][k] ;
}
}
for (k=0; k<colonne; k++)
{
Media[k] = (ArrayPower[k]/righe);
}
return Media;
}
This is how I call the function from the main:
VettoreMedia = CalcMeanPower(VettoreMedia, RefMeanPower, num_mean, N);
,where the variables are defined as follows:
int* RefMeanPower[N];
int* VettoreMedia;
int N=4, num_mean=5;
When I try to run the program it returns me a segmentation fault while trying to do:
for (k=0; k<colonne; k++)
{
Media[k] = (ArrayPower[k]/righe);
}
Could you please explain me what I'm doing wrong? I've searched through the net but I can't find the answer. This function is only a little piece of my C program, but I'm sure it faults in this cycle!
Please Help..
u have not initialized VetorreMedia befor passing to the function. since this is not initialized,Media also is pointing to unknown location so segmentation fault. VetorreMedia should have some default value.
If you run this in a debugger you will see where your segfault is occurring and be able to solve it from there.
Google gdb cheatsheet to get started.
You need to reserve memory for your variables/arrays.
RefMeanPower is just a array of plain uninitialized pointers. And VettoreMedia is just a plain uninitialized pointer.
for(int i = 0; i < N; ++i)
RefMeanPower[i] = malloc(sizeof(int) * num_mean);
// don't forget to free after usage
for(int i = 0; i < N; ++i)
free(RefMeanPower[i]);
Where you get RefMeanPower[N][num_mean] so swap k and i as indices or N and num_mean on creation.
and for VettoreMedia you can do
VettoreMedia = malloc(sizeof(int) * N);
// don't forget to free after usage
free(VettoreMedia);
or
int VettoreMedia[N];
// frees automatically when leaving scope

Resources