#Segmentation fault caused by dinamic memory (probably)

486 messages · Page 1 of 1 (latest)

midnight breachBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

obtuse vapor
#

Could you provide more information on where the segmentation fault happens? Maybe include the error.

fallow raven
#

it just says segmentation fault core dumped

obtuse vapor
#

There's no additional information at all?

fallow raven
#

when i run it it just says that

#

i use codeblocks and it says this

obtuse vapor
#

Sometimes you get some debugging information.

fallow raven
#

when i try to debub

#

debug

#

it makes no sense because even when i put a breakpoint at the start where i define the struct it gives me seg

obtuse vapor
#

Okay so one thing to test is

#

Check if the [i] index is actually being checked to exist.

#

You increment i in the for loops

#

but you're not checking if the index actually exists, right?

fallow raven
#

true

obtuse vapor
#

What if curso[i] does not exist when you go to ```c
if(cursos[i].curso_codigo == NULL){
puts("memória excedida");
exit(-1);
}

#

It'll throw an error since it can not evaluate cursos[i], and therefor can't check cursos[i].curso_codigo

fallow raven
#

because its sequencial?

obtuse vapor
#

Yes, it first checks if cursos[i] exists

#

maybe add this

fallow raven
#

but it should exist no? i am pulling it from main?

obtuse vapor
#
if(cursos[i] && cursos[i].curso_codigo == NULL)
fallow raven
#

it gives me an error

#

and when i declare the i inside the function it gives me a warning saying its not being used

obtuse vapor
#

I'm not too sure then, can't quickly spot

fallow raven
#

i think that maybe the error might be in pulling the n_cursos from the main

obtuse vapor
#

How did you even get that far without spotting a segfault

fallow raven
obtuse vapor
#

what you can do is try to printf("%d, i)

#

debug it by adding a printf statement inside the loop

#

see where it beaks

#

breaks

#

print every iteration value

fallow raven
#

it doesnt reach the line after for

obtuse vapor
#

1, 2, 3 etc and see where it breaks

fallow raven
#

even

obtuse vapor
#

What is the n_cursos value?

fallow raven
#

it didnt reach the print

obtuse vapor
#

try and print the n_cursos value before the for loop

fallow raven
#

and i am pulling it from main

obtuse vapor
#

But

#

What is it's value before going into the loop

#

you just said the loop isn't doing anything

#

as it's not printing

fallow raven
#

its not that loop

#

its the while loop with a get line

obtuse vapor
#

I'm confused now.

obtuse vapor
#

Cause it's not printing the i

fallow raven
#

this is the snippet of the code that counts n_candidatos and n_cursos

fallow raven
#

but it doesnt reach the print

#

bc of the segmentation default

obtuse vapor
#

so now we know which function is not getting reached

#

That's progress

#

Honestly, just keep doing the printf's

#

And figure out where it's actually breaking

#

like the exact line

#

It'll make it much easier for you to figure out what's going wrong

#

And it's a great example to learn from

fallow raven
#

but if always stops before the prints i will never understand what its causing it

#

it always stops bc of the segmentation default

obtuse vapor
#

Exactly

#

So find a place that does not stop before the printf

#

you need to figure out where exactly your code is bugging out

#

So follow your main's function calls

#

See which gets called first, check a printf there

#

gets printed? Move to next function being called

#

untill it doesn't print

#

and you have your area to look at

#

Might sound demotivating, but I do it on the regular.

fallow raven
#

but i think it doesnt reach the main right? because the 1st function is not printing

obtuse vapor
#

Then move the printf up higher

#

inside the main

#

untill it does print

#

and figure out which function is failing

#

or not even function, but maybe it's an assignment to a variable

#

so just keep moving the printf untill it prints

fallow raven
#

oh the main should be the 1st thing and the functions should be after the main?

obtuse vapor
#

What I mean is.

#

printf("This code has been reached without any errors.");

#

place that inside your main

#

Preferably after declaring your variables.

#

And see if it prints, if it does, move it down another line.

#

Untill it does not print

#

When it stops printing, you know which line/function is causing your error

fallow raven
#

its not printing in the 1st line of main aahhaha

#

thats the problem

obtuse vapor
#

What

fallow raven
#

ye

obtuse vapor
#

Can you show me your code with the prntf

#

and the result of running the program

fallow raven
#

i am sry for taking so much of your time but i am desesperate

obtuse vapor
#

Did you save the file...?

#

And you need to end the printf with ;

fallow raven
obtuse vapor
fallow raven
obtuse vapor
#

No ; here.

obtuse vapor
#

You need to save your code changes before executing it

fallow raven
obtuse vapor
#

what are those green lines

#

in your editor

fallow raven
#

i couldnt tell you realy

#

i dont know

obtuse vapor
#

what editor are you using

#

Cause those green lines seem to be indicating unsaved changes.

fallow raven
#

codeblocks from virtual machine

obtuse vapor
#

Nevermind, green lines are modified + saved

#

Honestly, it seems like you're program is not even running

fallow raven
#

its been working well

#

i dont think its the program

obtuse vapor
#

How can it be working well if your main function is not executing?

#

I mean, there's obviously something sketchy going on. Almost like it's a different file.

fallow raven
#

the reason i dont think its the program fault its because the university i attend tells us too use it

hallow trout
#

oh by program you mean the IDE

#

not your program

obtuse vapor
#

I meant his code

#

But he seems to mean IDE

#

😦

#

The IDE seems okay, I see Valgrind in there and error logs.

#

warning flags

#

But how can his main function not execute the printf method

#

even if it's the first line.

hallow trout
#

maybe that little window only prints stderr

#

not stdout

obtuse vapor
#

Oof

hallow trout
#

try running the program straight from a terminal

obtuse vapor
#

Not sure if he knows how

fallow raven
#

ok i think i know

#

i need to compile ot

#

it

obtuse vapor
#

Yes

#

gcc/cc

#

not sure

#

which one you use

fallow raven
#

gcc

obtuse vapor
#

same here :p

fallow raven
#

but the command to run is which ?

obtuse vapor
#

gcc filename

hallow trout
#

The IDE is already compiling it probably, yoiu just need to find the binary and run it

obtuse vapor
#

ah

#

./prog_name ?

#

default is ./a.out?

hallow trout
#

yes, idk how that IDE does it specifically tho

obtuse vapor
#

Me neither, first time seeing it.

#

I just use VSCode

fallow raven
obtuse vapor
#

lel

fallow raven
#

i can run with valgrind

obtuse vapor
#

try that

fallow raven
#

its like --valgrind-leakcheck=full ?

obtuse vapor
#

Probably

#

Brb, be back in 10.

fallow raven
#

i have to ask it to a colleague lemme see

hallow trout
#

use fprintf with stderr instead of prinft

#

to debug

fallow raven
hallow trout
#

you are writing to NULL somewhere

fallow raven
#

i am checking if its null

#

ah

#

could it be this

#

the 2 ==

#

nah its not i am tweaking already

#

everytime i used null was just to check if something was null i dindnt atribute the null value to anything

hallow trout
#

strtok might return NULL

#

have you checked taht

fallow raven
#

how do i check taht

#

that

hallow trout
#

when you do token = strtok(...)

fallow raven
#

yes

#

in line 123

hallow trout
#

add an if statement checking whether NULL == token

fallow raven
#

oh ok

hallow trout
#

in all of your strtok instances

fallow raven
#

that makes sense

hallow trout
#

maybe you should try writing this as a smaller program, with less 'moving pieces' so that you can get one thing right at a time

fallow raven
#

idk where it was from

#

but when i ran it

#

i got an error in print

#

i lost it

#

i am trying to find it

#

iu think the error is in opening the file

#

tbh

#

it should be about these variables

#

because it printed Error segmentation fault

obtuse vapor
#

I just ran your code.

#

There are several errors.

fallow raven
#

ok know it showed this

obtuse vapor
#

.main.c:269:10: error: unused variable 'nota_curso' [-Werror,-Wunused-variable] char nota_curso [i];

fallow raven
#

its a start

obtuse vapor
#

The Error it's throwing is because it probably can not find the .csv files.

#

And besides that you have leaks.

fallow raven
#

but they are with the right name and in the right directory

obtuse vapor
#

Show me your directory

fallow raven
#

arent the leaks because of not freeing

obtuse vapor
#

Yes, you're allocating memory

fallow raven
#

well i didnt write anything to free them yet

obtuse vapor
#

Okay let's check if those .csv's are readable.

#

In the terminal inside your directory

#

can you do ls -la

#

And show me output ?

hallow trout
#

you should check whether fopen is succesful

#

to begin with

fallow raven
#

ok i ll do it

fallow raven
obtuse vapor
fallow raven
hallow trout
#

if you have an error with fopen you should probably exit(EXIT_FAILURE) right there

#

instead of pritning an error

obtuse vapor
#

Okay, your .csv files have read and write access.

hallow trout
#

(i nthis specific case)

obtuse vapor
#

no issue there

hallow trout
#

    while (fgets(line, 300,fp_candidatos)){
          if(joao == 0){
            joao = 1 ;
            continue;
          }
          n_candidatos++ ;

    }
    joao = 0 ;
    while (fgets(line, 300,fp_curso)) {
          if(joao == 0 ){
            joao = 1;
            continue;
          }
          n_cursos++;

    }
``` whats the point here?
#

of joao

obtuse vapor
#

jao is always 0 first time

#

heh

fallow raven
#

the point is to read trought the lines in a loop to find out how many n_cursos is and n_candidatos

#

without the need of an input

hallow trout
#

but why do you skip one

fallow raven
#

bc the file in excel

#

has the 1st line that is

#

like the names of the collumns

#

the problem now is on the function memoria_candidatos

hallow trout
#

ah ok. you could have just decremented the variable you know? lol

#

but ok doesnt matter

#

so the program enters that function but crashes isnide that?

fallow raven
#

idk what happened but its not crashing

#

but its not running well

#

i am going trough each line

#

with watches

#

but something doesnt match here

hallow trout
#

how do you allocate the array cursos

fallow raven
#

the token changes from 2 to 19 instead of 18

fallow raven
hallow trout
#

how do you allocate candidatos

fallow raven
#

with the function

#

memoria_candidatos and memoria_cursos

hallow trout
#

no, that one fills in the pointers inside each 'Curso' struct

#

but you are passing to that function an array

#

looks like you are using VLA

fallow raven
#

VLA?

hallow trout
#

variable length array

fallow raven
#

ye

#

it can be extended

hallow trout
#

could you post again what the current state of your file is

fallow raven
#

the current state of my file?

hallow trout
#

yes

#

your code

fallow raven
#

ah

#

u want me to copy to here?

hallow trout
#

yes

#

and maybe whats in the csv files too

#

for good measure

fallow raven
#

i changed the name of the files

#

in my directory

#

and theres an error that i cannot explain , its so stupid

hallow trout
#

what is it?

fallow raven
#

on the watches it reads the line like 2 19 19 19

#

instead of 2 18 18 18

#

like wtf

hallow trout
#

lol

#

thats spooky

#

            token = strtok(line, ",");
            if( token == NULL){
                puts("memória excedida");
                exit(-1);
            candidatos[a].id_candidato = atoi(token);
            }
#

code under exit will never be run

#

you misplaced the }

fallow raven
#

ye i put the bracket in the wrong spot

#

i put it wrong in all of them

#

f

hallow trout
#

lol

#

you should probably write a function to take care of all that

#

also hold on why are you using atoi with id_candidato

fallow raven
#

glad u sad that bc i am finding so much erros

#

bc its an integer

hallow trout
#

oh i see

#

i thought that was their name

fallow raven
#

no its just a number

#

beetwen 1 and 60000

hallow trout
#

yeah, the compiler should have complained otherwise

fallow raven
#

bruh u wont believe

#

i fixed the erros u were talking abut

#

and now its segmentation fault again

#

its because the token cant acess memory

#

what can be causing this

hallow trout
#

does it segfault or does it exit

fallow raven
#

segfault

#

its not exctracting the value from the excell

hallow trout
#

what does funcao do

#

shouldn't it come AFTER yyou allocated memory

fallow raven
#

its suposed to read the valus from excel

#

values

hallow trout
#

because you are using strcpy in there, but the function gets called before memoria_candidato

#

you are strcpying to a pointer that has not been initialized yet

fallow raven
#

ok so i should put this function above?

hallow trout
#

funcao is a pretty bad name for a function btw lmao

fallow raven
#

funcao is function in portuguese

#

hahaha

hallow trout
#

i know lol

#

it should be a bit more descriptive

#

of what it does

fallow raven
#

i ll change a lot of things such as names of variables too

#

but i was trynna get the code to work

#

and after this starts working i still have to learn how to print it to a file

#

4 to be specific

#

and i have till 23.59

#

its 18.17 here

hallow trout
#

oof

#

lol

fallow raven
#

but i should put the funcao above the memoria_candidatos

#

?

hallow trout
#

i am not sure but i think funcao is mean to fill in the date into the candidatos array, right?

fallow raven
#

yes

hallow trout
#

but how do you fill in the data into the array if the memory of the array isnt there

fallow raven
#

that makes sense

#

i am going to move it

hallow trout
#

you should probably do all of it in a single function

#

something like this:

fallow raven
#

you think?

#

i mean it makes sense

obtuse vapor
#

How did you guys do trying to solve the errors?

fallow raven
obtuse vapor
#

Screw the deadline, focus on actually learning as you debug this issue.

#

Imagine racing against the clock and forgetting all the issues you encountered.

#

That's a waste of time.

fallow raven
#

thats true

#

but i want 40%

hallow trout
#
            token = strtok(NULL, ",");
            if( token == NULL){
                puts("memória excedida");
                exit(-1);
            }
            // now allocate memory to hold a copy of token
            char * copy = malloc(strlen(token)+1); //and hten check if null
candidatos[a].curso = copy;
            strcpy(candidatos[a].curso, token);
obtuse vapor
#

Writing to a file is not that hard

#

Just learn slowly and understand the concepts

fallow raven
obtuse vapor
#

I'm leaving now, will be on in like an hour or two.

#

Good luck

fallow raven
#

tks a lot

#

but how do i merge the while and the for loop

hallow trout
#

just dont use a for loop

fallow raven
#

just use the while?

hallow trout
#

or dont use a while loop

#

you already know how many lines you need to process, right?

#

just process them in one go. with a for loop

fallow raven
#

the number of lines changes from file to file

#

oh ok

#

i understand what ur saying

#

something like for(i=0;i<n_cursos;i++)

#

but i need the while loop to exctract the data,no?

#

i dont need to save in memory integers right?

hallow trout
#

you just need one loop

#

something like

for ( i = 0 ...)
{
  fgets(line ...); // get a line
  token=strtok(line,","); // get a token
  newstr=malloc(strlen(token)+1) //allocate space for token
  strcpy(newstr,token);
 
 candidato.something = newstr;
// and repeat for the other entries in the struct
}
fallow raven
#

i think that would work

#

the problem with it

hallow trout
#

thats the only way you can properly use malloc btw, if you just use hardcoded values for malloc calls you are just wasting time.

fallow raven
#

the newstr is a pointer for each of the variabkes candidato has?

#

so i will have to have lots of newstrs?

hallow trout
#

hmm not necessairly. newstr can be a single char * variable, and whenever you need to allocate a new string for your strict, you use the same variable

fallow raven
#

and when u said candidato.something u meant candidato[i].something right?»

hallow trout
#

theres no problem if you overwrite old values because you have already saved that in the strung

#

oh yeah

fallow raven
#

oh ok

fallow raven
#

and its probably very efficient that way right?

hallow trout
#

probably, but the best thing about it is that you get to use strlen(token) to get what the actual length of the string is

fallow raven
#

what does the strlen does

hallow trout
#

that way you could store a string of length 1000 if you wanted

#

strlen calculates the length of a string

#

strlen("hi") returns 2

fallow raven
#

so i dont need to declare the size of the array as i was doing in the malloc?

hallow trout
#

what do you mean?

fallow raven
#

like this 10 is going to be calculated by the strlen

hallow trout
#

oh yeah. instead of that hardocded 10, you get a numbers thats calculated from the input you get from your file

fallow raven
#

oh ok thats cool

hallow trout
#

btw sizeof(char) is just 1. no need to use that

fallow raven
#

i ll change this function for the one u came up with

hallow trout
#

i advice you to rewrite the entire thing from scratch

fallow raven
#

token=strtok(line,","); // get a token
newstr=malloc(strlen(token)+1) //allocate space for token
strcpy(newstr,token);

candidato.something = newstr;

#

thse are the things that will repeat troughout the function right?

#

and doesnt this : candidato.something = newstr, | need to come b4 the newstr=malloc(strlen(token)+1) //allocate space for token

hallow trout
#

yeah. of course sometimes you have integer entries so instead of strcpy you'd use something else

#

nonono

#

that would be giving the struct an uninitialized value

hallow trout
#

what you want to do is

  1. get the token
  2. calculate its length
  3. allocate enough memory to hold a copy of the token
  4. copy the token into the newly allocated memory
  5. store the pointer to the newly allocated memory in your struct
hallow trout
#

but for the time being you can use atoi i guess

fallow raven
#

And how do I alocate memory for the integers

#

I don't need to right?

hallow trout
#

nope you dont need to

#

the struct has that memory within it

#

it also has memory for a pointer, but not necessarily for what the pointer points at

fallow raven
#

So the candidatos[I].id_candidato which is an integer will be accessible with any i

hallow trout
#

i dont understand what you mean

fallow raven
#

i was just asking if the code will always know the id_candidato of every i

#

i being the index

fallow raven
hallow trout
hallow trout
#

strlen return the number of non \0 characters

#

but you need the delimiter there i nthe end

fallow raven
hallow trout
#

probably, just to so you know somethings off if you make a mistake

#

i think you should write a function that looks like this:

fallow raven
#

like this?

hallow trout
#
candidato processline ( char * line )
{
  candidato currentcandidato;
  strtok(blabla); malloc ; strcpy .....
  currentcandidato.something = newstr; //or atoi) 
strtok(blabla); malloc ; strcpy .....
  currentcandidato.something = newstr; //or atoi)
 strtok(blabla); malloc ; strcpy .....
  currentcandidato.something = newstr; //or atoi)
  ....
return currentcandidato;
}
#

Ie write a function that give a line of input from the csv file, returns a struct with all the data from the input line

#

that way you can later do a for loop:

#
for (i=0...){
  fgets(line ...)
  candidatos[i] = processline(line);
}
#

instead of having the loop related stuff mixed with the data processing stuff

fallow raven
#

for (i=0...){
fgets(line ...)
candidatos[i] = processline(line);
}

#

candidato processline ( char * line )
{
candidato currentcandidato;
strtok(blabla); malloc ; strcpy .....
currentcandidato.something = newstr; //or atoi)
strtok(blabla); malloc ; strcpy .....
currentcandidato.something = newstr; //or atoi)
strtok(blabla); malloc ; strcpy .....
currentcandidato.something = newstr; //or atoi)
....
return currentcandidato;
}

#

it would stay like this

#

?

hallow trout
#

oh you are meant to fill in the gaps lol

fallow raven
#

yes ik

#

i was justa sking about the format

hallow trout
#

what i mean is, currently in your function funcao you are at the same time dealing with an array of candidatos, and with the data processing of each line

fallow raven
#

and what is candidato processline(char * line)?

hallow trout
#

thats a function definition

#

a function that returns a 'candidato'

#

you input a line, you get back your struct

fallow raven
#

what does returning the currentcandidato do?

hallow trout
#

what the function does is define a local variable currentcandidato

#

and it takes data from the 'line' and fills the local variable with data from there

fallow raven
#

ah and alocates all the memory for that specific candidato?

#

ah ok

hallow trout
#

yes

fallow raven
#

ok nuce

#

noice

hallow trout
#

then you return the struct with all the data already filled in

fallow raven
#

yes that very smart

fallow raven
hallow trout
#

sorry i was just trying to write in shorthand

hallow trout
#

except with currentcandidato instead of candidato[a]

fallow raven
#

~where should i put the strlen

hallow trout
#

in malloc

#

malloc (strlen(token) +1);

fallow raven
#

and i am not rly understand if the malloc stays on a line alone or if not

hallow trout
#

it doesnt matter in C

fallow raven
#

so the strcpy can be on the same line as malloc?

hallow trout
#
int i = 0 ; i += 4; 
//same as

int i = 0;
i+=4;
#

put them each in a different line

#

for readabilty

#

but it doesnt actually matter to the C language

fallow raven
#

and i am still going to use this char * newstr = malloc(strlen(token)+1); //and hten check if null
currentcandidato.curso = newstr;
strcpy(currentcandidato.curso, token);

#

but not with copy there obiously

#

and curso changes troughout

hallow trout
#

instead of candidatos[a] you would use the local vairable

#

currentcandidato

fallow raven
#

ah ok

hallow trout
#

and you could call that copy or newstr or whatever

#

its the same idea

#

I gotta go. my advice is dont try getting everything in one step. try to incrementally get where you need to be. write a program that just processes one of the files, or only a single line, and then go to the next step. no need to get everything right from the getgo

#

good luck!

fallow raven
#

tks a lot man

fallow raven
#

@obtuse vapor can u help me understand something cardiou coded

obtuse vapor
#

?

#

what part

#

Haven't been following it lately, bit busy with own assignment too

fallow raven
#

can u understand that this is what he was trying to do

#

i am not 100%sure

#

and my debugger is not running

fallow raven
#

@obtuse vapor are u there man

#

its 30 min to enter

#

and i rly need to sort one thing

obtuse vapor
#

Sorry man I got stuck on my own project, didn't get to read your messages.

#

I hope you figured it out in the end..

fallow raven
#

i did

obtuse vapor
#

Nice!

midnight breachBOT
#

This question is being automatically marked as stale.
If your question has been answered, run !solved.
If your question is not answered feel free to bump the post or re-ask.
Take a look at !howto ask for tips on improving your question.

obtuse vapor
#

!solved