Why is this happening? (memory lose(?)) - c

I can't seem t find why my program is crashing with segmentation fault.
char *nom;
char **tmp=&nom;
printf("Creando ruta ...\n");
printf("\nIntrodueix el id de la ruta: ");
int ID=demanaInt();
int existe=checkIfRutaExisteix(ID);
if(existe==1){
printf("Ja existeix una ruta amb aquesta ID (id ha de ser unica)");
return;
}
printf("\nIntrodueix el nom de la ruta: ");
demanaString(tmp);
printf("\nIntrodueix el numero de parades: ");
int numParades=demanaInt();
Ruta *r = malloc(sizeof(*r) + sizeof(Parades) + sizeof(*(r->parades.coordenades)) * numParades + sizeof(nom));
strcpy(r->nom, nom);
if(numParades!=-1){
r->parades.numParades=numParades;
}else{
return;
}
int c;
for(int i=0;i<numParades;i++){
r->parades.coordenades[i] = malloc(sizeof(*(r->parades.coordenades[i])*2));
printf("Introdueix la coordenada x de la parada numero %d: ", i);
c=demanaInt();
if(c==-1){
return;
}
r->parades.coordenades[i][0]=c;
printf("Introdueix la coordenada y de la parada numero %d: ", i);
c=demanaInt();
if(c==-1){
return;
}
r->parades.coordenades[i][1]=c;
printf("%d, %d\n", r->parades.coordenades[i][0], r->parades.coordenades[i][1]);
}
printf("Introdueix ID regio: ");
r->IDregio=demanaInt();
r->ID=ID;
guardaRutaCSV(r);
Just before asking for an int evreything is correct, but after that I seem to lose information.
This is my output of GDB:
Creando ruta ...
Introdueix el id de la ruta: 4
Introdueix el nom de la ruta: ref
Introdueix el numero de parades: 3
Introdueix la coordenada x de la parada numero 0: 1
Introdueix la coordenada y de la parada numero 0: 2
1, 2
Introdueix la coordenada x de la parada numero 1: 3
Introdueix la coordenada y de la parada numero 1: 4
3, 4
Introdueix la coordenada x de la parada numero 2: 5
Introdueix la coordenada y de la parada numero 2: 6
5, 6
Breakpoint 1, generarRuta () at ruta.c:90
90 printf("Introdueix ID regio: ");
(gdb) p r->parades.coordenades[0][1]
$1 = 2
(gdb) n
91 r->IDregio=demanaInt();
(gdb) p r->parades.coordenades[0][1]
$2 = 2
(gdb) n
Introdueix ID regio: 99
92 r->ID=ID;
(gdb) p r->parades.coordenades[0][1]
No se puede acceder a la memoria en la dirección 0x555500000067
Why is no longer accesible the information inside the array?
PD: here is the struct:
typedef struct _parades{
int numParades;
int *coordenades[];
} Parades;
typedef struct _ruta{
int ID;
Parades parades;
int IDregio;
char nom[];
} Ruta;

A struct with a flexible array member (array with []) can't be used as a member in another struct. From the C spec (6.7.2.1):
A structure or union shall not contain a member with incomplete or function type (hence,
a structure shall not contain an instance of itself, but may contain a pointer to an instance
of itself), except that the last member of a structure with more than one named member
may have incomplete array type; such a structure (and any union containing, possibly
recursively, a member that is such a structure) shall not be a member of a structure or an
element of an array.
The shall here indicates that the compiler should be giving you a diagnostic message for this code. (Parades being such a structure means it can't be used as a member in Ruta)

Related

Scanf only input 1 value out of the 4 & called object is not a function or function pointer error

So I tried to put a program to calculate triangle height here it is :
#include <stdio.h>
void main()
{
float shorty_to_lefty=0.0f , lofty_to_tree=0.0f, lofty=0.0f , shorty=0.0f , arbre=0.0f;
printf("\nRentrer la distance entre le petit et le grand:" );
scanf("%0.2f", &shorty_to_lefty);
printf("\nRentrer la distance entre le grand et l'arbre:" );
scanf("%0.2f", &lofty_to_tree);
printf("\nRentrer la taille du petit" );
scanf("%0.2f", &shorty);
printf("\nRentrer la taille du grand:" );
scanf("%0.2f", &lofty);
arbre= lofty+(shorty_to_lefty/lofty_to_tree)(lofty-shorty)/shorty_to_lefty;
printf("La taille de l'arbre est de %.2f m", arbre);
}
But the problem is when I launch it the scanf only input 1 value and not the rest ex:
Rentrer la distance entre le petit et le grand:
2
Rentrer la distance entre le grand et l'arbre:
Rentrer la taille du petit
Rentrer la taille du grand:La taille de l'arbre est de -1.#J m
and in the last float arbre= lofty+(shorty_to_lefty/lofty_to_tree)(lofty-shorty)/shorty_to_lefty when i try to compile I get this error
Arbre.c: In function 'main':
Arbre.c:16:34: error: called object is not a function or function pointer
arbre= lofty+(shorty_to_lefty/lofty_to_tree)(lofty-shorty)/shorty_to_lefty;
(there is an arrow under (shorty_to_lefty/lofty_to_tree))
Problem number 1:
Replace %0.2f with %f. The scanf format specifiers are similar to the ones of printf but not identical.
Problem number 2:
...lofty_to_tree) (lofty - shorty) ...
^
an operator is misssing here, possibly *

I'm getting negative output from a do-while loop, when it's supposed to stop at 0

I'm building a program for the problem set 1 of CS50x called "cash" that is written in C. I don't know how to make the function cant_de_monedas work on my main function, and when I tried to print the return "dinero" after each loop it keeps counting down even after it reachs 0.
//inclusión de librerías
#include <stdio.h>
#include <cs50.h>
//llamado de la función cant_de_monedas para su funcionamiento en main
float cant_de_monedas(float dinero, int monedas);
int main(void)
{
//input del dinero principal
float dinero = get_float("Insertar dinero: ");
//ajuste de monedas a 0
int monedas= 0;
//llama a la función cant_de_monedas
float cambio = cant_de_monedas(dinero, monedas);
printf("Cantidad de monedas de vuelto: %i\n", monedas);
}
//analiza las monedas necesarias de cambio para una cantidad de dinero variable en centavos de dolar
float cant_de_monedas(float dinero, int monedas)
{
//suma una moneda mientras el dinero sea mayor o igual a 25
do
{
monedas++;
dinero=dinero-25;
printf("%f\n", dinero);
}
while (dinero>=25);
//suma una moneda mientras el dinero se encuentre entre 25 y 10 incluído
do
{
monedas++;
dinero=dinero-10;
printf("%f\n", dinero);
}
while (dinero<25 && dinero>=10);
//suma una moneda mientras el dinero se encuentre entre 10 y 5 incluído
do
{
monedas++;
dinero=dinero-5;
printf("%f\n", dinero);
}
while (dinero<10 && dinero>=5);
//suma una moneda mientras el dinero se encuentre entre 5 y 1
do
{
monedas++;
dinero=dinero-1;
printf("%f\n", dinero);
}
while (dinero<5 && dinero>1);
//suma una moneda mientras el dinero sea 1
do
{
monedas++;
dinero=dinero-1;
printf("%f\n", dinero);
}
while (dinero==1);
return monedas;
}
The output that I get from it is:
$ ./cash
Insertar dinero: 51
26.000000
1.000000
-9.000000
-14.000000
-15.000000
-16.000000
Cantidad de monedas de vuelto: 0
I have three remarks:
You seem to be working with floating point numbers, while there can be quite some rounding issues with those. I'd advise you to work with integer values only.
If you do need to work with floating numbers, I advise you to use double instead of float.
Instead of a do-while, just use a while (imagine the condition is never met, then the loop is not executed at all).

matrix of characters in c , I need to pass a matrix to a function as a parameter

I need to pass a matrix to a function as a parameter but when checking if it is happening or not I try to print the value of the matrix [1][1] and it does not work
int Cabe_proceso(int pag, int cel,int pal,char Memoria_fisica[1][pal-1]){
printf("[%s]\n",Memoria_fisica[1][1]);
}
int main(void){
int palabras, celdas;
printf("Ingrese la cantidad de palabras soportadas por la memoria principal\n");
scanf("%i",&palabras);
printf("Ingrese la cantidad de palabras que define el tamano de un marco de paginas\n");
scanf("%i",&celdas);
int marcos =palabras/celdas;
int i,j,aux=celdas,m=1;
if(palabras%celdas ==0){
marcos= marcos;
}else{
marcos++;
}
char *Memoria_fisica[1][palabras-1];
for(i=0;i<1;i++){
for(j=0;j<palabras;j++){
Memoria_fisica[i][j]= "0";
}
}
for(i=0;i<1;i++){
for(j=0;j<palabras;j++){
printf("[%s]\n",Memoria_fisica[i][j]);
if(j==aux-1){
printf("--------------marco %i\n", m);
aux=aux+celdas;
m++;
}
}
if(palabras%celdas!=0){
printf("------------------marco %i\n",marcos);
}
}
printf("%i\n",celdas);
Cabe_proceso(1,celdas,palabras,Memoria_fisica);
return 0;
}
I included the bookstores stdio.h , stdlib.h, strings.h

Why is my code crashing? [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
I've got a pretty basic question, why is my code crashing? I'm learning to use pointers and I really don't know why the code crashes after I enter the values of x1,x2,y1 and y2 (this happens in case 3 of the second switch). I've looked everywhere and I can't find a reason. I need to send the values entered in function menuLR, case 3 to the function DistDosPuntos, an then return the values to menuLR,case 3.
Here's my code.
Some of the code is in spanish, however it's not relevant to know how the code is working. In advance thanks for your help and patience, I know this is quite dumb, but I've tried several methods and haven't been able to either solve or understand the problem
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
void menu1();
void menuLR();
void DistDosPuntos();
void menu1()
{
int a;
float m,x1,x2,y1,y2,k,v,d;
printf("MENU PRINCIPAL\n");
printf("1.- La línea Recta \n");
printf("2.- La circunferencia \n");
printf("3.- Coordenaas Polares \n");
printf("4.- Salir\n");
scanf("%d",&a);
switch(a)
{
case 1:
menuLR(&m,&x1,&x2,&y1,&y2,&k,&v,&d);
break;
case 2 :
// ;
break;
case 3 :
//;
break;
case 4 :
break ;
}
}
void menuLR (float *m,float*x1,float *x2,float *y1,float*y2,float*k,float *v,float *d)
{
int b;
printf("LA LINEA RECTA\n");
printf("1.- Ecuación de la recta dada su puendiente y un punto de la misma \n");
printf("2.- Ecuación de la recta que pasa por dos puntos\n");
printf("3.- Distancia entre dos puntos del plano \n");
printf("4.- Punto medio entre dos puntos del plano\n");
printf("5.- Perímetro y área de un triángulo en un plano\n");
printf("6.- Regresar al menú principal\n");
scanf("%d",&b);
switch (b)
{
case 1 :
printf("Introduzca la pendiente de la recta m y el punto P1(x1,y1)\n");
printf("Introduzca m\n");
scanf("%f",m);
printf("Introduzca x1\n");
scanf("%f",x1);
printf("Introduzca y1\n");
scanf("%f",y1);
printf("La ecuación de la recta es:\n");
printf("y-y1 = m(x-x1)\n");
printf("Sustituyendo valores:\n");
printf("y-%f = %f (x-%f) \n" ,*y1,*m,*x1);
printf("Desarrollando y despejando:\n");
*k = ((*m)*(*x1));
printf("y-%f = %fx-%f)\n",*y1,*m,*k);
*v= -*k+*y1;
printf("y=%fx+(%f)\n",*m,*v);
printf("La ecuación de la recta en la forma general 'y=mx+b' es:\n");
printf("y=%fx+(%f)\n",*m,*v);
break;
case 2 :
break;
case 3 :
printf("Introduzca el punto en el plano P1(X1,Y1)\n");
printf("x1:");
scanf("%f",x1);
printf("y1:");
scanf("%f",y1);
printf("Introduzca el punto en el plano P2(X2,Y2)\n");
printf("X2:\n");
scanf("%f",x2);
printf("Y2:\n");
scanf("%f",y2);
DistDosPuntos(&x1,&x2,&y1,&y2,&d);
printf("La distancia entre los puntos P1 y P2 es:\n %f",*d);
break;
case 4 :
// exit ;
break ;
}
}
void DistDosPuntos(float *x1,float *x2, float *y1, float *y2,float *d)
{
*d = sqrt(pow((*x2-*x1),2) + pow((*y2-*y1),2));
}
int main()
{
int a,b;
float m,x1,y1,k,v,d,y2,x2;
menu1(&b,&x1,&y1,&x2,&y2,&m,&k,&v,&d);
DistDosPuntos(&x1,&x2,&y1,&y2,&d);
return 0;
}
I think you are taking the address of a pointer and passing as a pointer in this section:
printf("Y2:\n");
scanf("%f",y2);
// wrong? x1,x2... are *float; Remove the &s
DistDosPuntos(&x1,&x2,&y1,&y2,&d);
The arguments of the function menuLR are are variables with the names x1, etc. These are of type (float *). They happen to have the same name, (though different types), than the variables in your main function. That's why in one case you need no &, whereas in the main function you do.

Getting wrong value in variable in C using structs

I have problems getting the right value for cociente; every time I run it, cociente is printed as 1 but that is not the value I want to assign it, this is the code where I print:
printf("\nEl valor del cociente es: %d",(polinomio_->polinomio->cociente));.
This is my code:
#include<stdio.h>
#include<stdlib.h>
typedef struct termino
{
int exponente;
float cociente;
} termino;
typedef struct polinomio
{
termino* polinomio;
int size;
} polinomio;
void multiplicarEscalar(int escalar, termino* term){
term->cociente = (term->cociente)*(float)escalar;
}
main()
{
int size_;
termino* terminos;
int cociente_temporal;
polinomio *polinomio_;
//polinomio_ = malloc(sizeof(polinomio));
//printf("%d",(sizeof(polinomio_)*2));
printf("Bienvenido al cálculo de operaciones usando 1 polinomio.\n");
printf("Ingrese la cantidad de términos que tendrá el polinomio.");
scanf("%d",&size_);
terminos =(termino*) malloc(sizeof(termino) * size_);
polinomio_ = (polinomio*) malloc(sizeof(polinomio) );
polinomio_->polinomio = terminos;
polinomio_->size = size_;
printf("Ingrese el cociente 0:\n");
scanf("%d",&cociente_temporal);
polinomio_->polinomio->cociente = cociente_temporal;
//multiplicarEscalar(2,polinomio_->polinomio);
printf("\nEl valor del cociente es: %d",(polinomio_->polinomio->cociente));
free(polinomio_);
}
You are using "%d" to print a float. That leads to undefined behavior.
Instead of
printf("\nEl valor del cociente es: %d",(polinomio_->polinomio->cociente));
use
printf("\nEl valor del cociente es: %f",(polinomio_->polinomio->cociente));
// ^^^

Resources