C program keep crashing - c

well i have this simple code, it asks the user how many numbers he wants to save, then it asks for the numbers, each time the user write the number the program prints the numbers that he has written already and it sort numbers from lowest to highest.
The problem is when the user tell the program to save more than 9 numbers, the programs just stops, if the user choose to save 8 or less number it works perfect. i don't know whats happening, I'll appreciate your help
The variables and other terms are based in my language, spanish, here are some translations:
function guardaNum: saves the number in the array
function ordena: sort array's numbers
function imprime: prints the array
contador: is a counter
cant: is the amount of number the users wants to save
thanks for your help!
#include <stdio.h>
int guardaNum(int *pnum,int lista[],int *pcontador);
int ordena(int lista[],int *pcontador);
void imprime(int lista[],int *pcant);
int main(void)
{
int cant, num, *pnum, lista[cant], i,contador,*pcontador ;
printf("Ingrese la cantidad de numeros que desea agregar a la lista: \n");
scanf("%d", &cant);
for(i=0;i<cant;i++)
{
lista[i]=-99;
}
for(i=0;i<cant;i++)
{
printf("Ingrese un Numero: ");
scanf("%d",&num);
pnum=&num;
contador=i;
pcontador=&contador;
guardaNum(pnum,lista,pcontador);
ordena(lista,pcontador);
imprime(lista,pcontador);
}
}
int guardaNum(int *pnum,int lista[],int *pcontador)
{
lista[*pcontador]=*pnum;
return 0;
}
int ordena(int lista[], int *pcontador)
{
int i,j, temp;
for(j=0;j<*pcontador;j++)
{
for(i=0;i<*pcontador;i++)
{
if(lista[i]>lista[i+1])
{
temp=lista[i+1];
lista[i+1]=lista[i];
lista[i]=temp;
}
}
}
}
void imprime(int lista[],int *pcontador)
{
int i;
for(i=0;i<=*pcontador;i++)
{
printf("%d\n",lista[i]);
}
}

do this:
int main(void)
{
int cant, num, *pnum, i,contador,*pcontador ;
int *lista;
printf("Ingrese la cantidad de numeros que desea agregar a la lista: \n");
scanf("%d", &cant);
lista = malloc(sizeof(int)*cant);
if(!lista){
perror("error on malloc");
exit(1);
}
//continue with your code
free(lista);
}
The problem with your code, is cant is uninitialized so the compiler doesn't know how much space is required for your array.
or you can do it this way:
scanf("%d", &cant);
int lista[cant]
//continue with your code

In this line:
int cant, num, *pnum, lista[cant], i,contador,*pcontador ;
You are using cant while it is uninitialized. You'll have to move your declaration of lista to be after you have input the size.

Note that you define the array with "cant" as size before you actually take it as an input.
You'll either need a max possible array size (and better check your input against it), or if you know how - allocate the array dynamically

Related

Seg fault when using scanf to define the size

I have a strange issue with my code :
I have a function generating a dynamic array of struct and only takes an int size as parameter.
It's work well until i try to add just a scanf("d";&size); to choose the size of my array, can't understand why i get a seg fault.
Note : There is no issue with compilation if i remove the line containing scanf
pokemon_t * createPkmDatabase( int taille){
printf("taille %d",taille);
pokemon_t *tableau=malloc(sizeof(pokemon_t)*taille);
...
...
}
int main(){
/*"taille" means size in french */
int taille=5;
printf("Saisir taille : ");
scanf("%d",&taille); /* <-- BREAKS EVERYTHING */
printf("valeur de taille : %d\n ",taille);
pokemon_t *database=createPkmDatabase(taille);
}
I don't get why changing the value of "taille" with a simple scanf change anything the value.
It doesn't even seems to enter in the function bc it doesn't even print the value of the size
There are no errors in the code shown.
Some remarks:
Use the correct type for sizes (size_t)
Always check the result of scanf and malloc
typedef struct {
int x,y,z;
}pokemon_t;
pokemon_t * createPkmDatabase(size_t taille){
printf("taille %d",taille);
pokemon_t *tableau=malloc(sizeof(*tableau)*taille);
return tableau;
}
int main(){
/*"taille" means size in french */
size_t taille;
printf("Saisir taille : ");
if(scanf("%zu",&taille) == 1)
{
printf("valeur de taille : %zu\n ",taille);
pokemon_t *database=createPkmDatabase(taille);
if(database)
{
printf("\nAllocation OK\n");
}
else
{
printf("\nAllocation FAILED\n");
}
free(database);
}
}
https://godbolt.org/z/ExjYe5G94

how to create a list which contains another list in C

so i wanted to create a sub list liste_fav of the main list abbones , and here is the structure
/*********************************/
typedef struct liste_fav
{
signed char numf[20];
struct liste_fav *suiv;
}liste_fav;
/***********************************/
typedef struct abonnes// lz structure principale
{
signed char num_c[20];
signed char operateur [20];
signed char profil[20];
int credit;
liste_fav *liste;// on sait pas si on doit mettre une etoile ici
struct abonnes *adr;
}abonnes;
si I have created a list that contains
i want to create the main list that contains the information about the subscriber and his information we have a pointer to another sub list that contains the favourite numbers of this subscriber .
I want to create an application that will allow the subscriber to manipulate his list of favourite numbers ( adding a new one , or deleting ...) , before this I have to record data in the main and the sub list . I've done this function that allow us fill up the information and also to full the list of favourite numbers , ,could you help please
P.S:I have a doubt that is : the affectation of the head of the sub list in the field (liste_fav *liste)
the functions used :
liste_fav *allouer_fav ()// allouer un espace memoire, elle retourne l'adresse de l'espace alloue
{
return ((liste_fav*)malloc(sizeof(liste_fav)));
}
abonnes *allouer_abo ()
{
return ((abonnes*)malloc(sizeof(abonnes)));
}
void creation_abo(abonnes **R)
{
signed char ope [20],numm[20],prof[20],rr[20],num[20];
abonnes *s,*tet;
liste_fav *b,*a;
//(*R)->liste=NULL;
int i,cred,no,eee;
int k=1;
printf(" number of nodes to create : ");
scanf("%d",&no);//the number of the nodes to link of the list abonnes
printf("~~~~~~~~~~~~\n");
*R= allouer_abo();
printf("operateur %d :",k);
scanf("%s",&ope);
aff_operateur(R,ope);//strcpy((p -> operateur ),r);
printf("his number:");
scanf("%s",&numm);
aff_num_c(R,numm);//strcpy((p -> num_c),num)
printf("donnez son credit : ");
scanf("%d",&cred);
aff_credit(R,cred);// p-> credit =n;
printf("donnez son profil : ");
scanf("%s",&prof);
aff_profil(R,prof);//strcpy((p->profil),f)
printf("creation de la liste des favoris: ");
printf("donnez le nombre de mailons a creer :");
scanf("%d",&eee);
printf("donnez le numero du contact 1 : ");
scanf("%s",&rr);
// abonnes *pp = (*R )->liste -> numf;
//strcpy(pp,rr);
abonnes *J= (*R)->liste ;//I have doubt here, it's supposed to be the affectation oh the head of the list in J
J=allouer_fav();//return ((liste_fav*)malloc(sizeof(liste_fav)));
affnum_fav_propre(J,rr);//strcpy((p ->numf ),n);
for ( i=1;i<eee;i++)
{
b=allouer_fav();
printf("donnez le numero du contact %d :",i+1);
scanf("%s",&num);
affnum_fav_propre(b,num);strcpy((p ->numf ),n);
aff_adr_fav_propre(J,b);// s -> suiv = q; s a pointer to list abonnes
}
aff_adr_fav_propre(b,NULL);
// we affected the heads, now we will affect the other structures to link
tet= R;
for(i=1;i<no;i++)
{
k++;
s= allouer_abo();
printf("_-__-_-_-_-_-_-_-_-_-_-_-_-_\n");
printf("give the operateur %d :",k);
scanf("%s",&ope);
aff_operateur(s,ope);
printf("donnez son numero : ");
scanf("%s",&numm);
aff_num_c(s,numm);
printf("the credit : ");
scanf("%d",&cred);
aff_credit(s,cred);
printf("the profil : ");
scanf("%s",&prof);
aff_profil(s,prof);
printf("creation of list favoris: ");
printf(" numbre of nodes you wanna create :");
scanf("%d",&eee);
printf(" numero the favoris 1 : ");
scanf("%s",&rr);
abonnes *J= (*R)->liste ;
J=allouer_fav();
affnum_fav_propre(J,rr);
for ( i=1;i<eee;i++)
{
b=allouer_fav();
printf("numero %d :",i+1);
scanf("%s",&num);
affnum_fav_propre(b,num);// strcpy((p ->numf ),n);
aff_adr_fav_propre(J,b);// s -> suiv = q;
J=b;
}
// aff_adr_fav_propre(b,NULL);
aff_adr_abo(R,s);//p-> adr=q
R=s;
}
aff_adr_abo(R,NULL);
aff_adr_fav_propre(b,NULL);
//s=NULL;
////tet=NULL; i was not sure
return ( tet);
}
Any help or proposition? hope you understood my problem
Yes, your doubt is correct. This line:
abonnes *J= (*R)->liste;
will not give you the desired result. Also, J needs to be a liste_fav*, not an abonnes*. Like so:
liste_fav* J = allouer_fav();
(*R)->liste = J;
You'll need to make the same change in the code below.
[As an aside, you'd make your life easier if you created a function which populated a single abonnes instance, and call it once for the head, then inside the "affect other structures to link" loop. As it is, you've got a large chunk of duplicated code which you'll have to fix twice.]
I have my doubt about aff_adr_fav_propre because you don't show the code, and the comment is wrong [it is not "a pointer to list abonnes", it is "a pointer to liste_fav"]. It needs to perform the following:
J->suiv = b;
J = b;
Also you fail to mention in your writeup is the problems you have with returning the results. You attempt to return tet, but you've declared creation_abo to be void. I think what you want to do is declare it as follows:
abonnes *creation_abo()
{
<existing code>
return tet;
}
The caller would look like this:
abonnes *master_list = creation_abo();
Your life would be improved with consistent indentation and descriptive variable names as well.

Why do I get random symbols when editing a text file in C?

I'm currently trying to create a program in C which creates, edits and prints a .txt document. At the moment I'm pretty new to C, but I've managed to create like half of the whole code.
The whole concept is:
Write data to a .txt file in list order
Add data to currently existing one (at the end of the list)
Delete items which are listed as X place or higher (x entered by keyboard)
Show on screen the whole list
So far I've managed to do 1 and 4, and I'm having a strange issue with 2. When I open the text file, I see random symbols all over the place. Any idea whats causing that? Also any advice for the 3rd point will be greatly appreciated.
Here is the code:
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
struct legumes
{
int id;
char name [35];
};
void Saisie (struct legumes b[20],int nbl);
void Affiche (struct legumes b[20],int nbl);
int main (){
FILE *fpr ;
FILE *fpw;
struct legumes b [20];
int i ;
int nbl;
char rep ;
fpw =fopen("program.txt","w");
fpr =fopen("program.txt","r");
if (fpr== NULL || fpw == NULL){
printf("\nError ");
exit (1);
}
printf("Combien de legumes vous voule entre ?");
scanf("%d",&nbl);
do
{
puts("Saisie, Affiche, Moyenne, Quitter ?");
printf("%c\n",rep=toupper(getch()));
switch (rep)
{
case 'S':Saisie(b ,nbl);break;
case 'A': Affiche (b , nbl);break;
}
}while (rep!='Q');
}
void Saisie (struct legumes b[20],int nbl){
FILE *fpw;
fpw =fopen("program.txt","w");
int i ;
printf("\nDonnez le donnes des legumes ");
for (i=0;i<nbl ;i++){
printf ("\nDonez le id de %d legume =",i+1);
fflush(stdin);
scanf("%d",&b[i].id );
printf("\nDonez le nom de %d legume = ",i+1);
fflush(stdin);
gets(b[i].name);
}
fwrite (b,sizeof(struct legumes),nbl,fpw);
fclose (fpw);
}
void Affiche (struct legumes b[20],int nbl){
FILE *fpr ;
int i ;
fpr =fopen("program.txt","r");
fread(b , sizeof(struct legumes),nbl,fpr);
printf("\n Legumes :");
for (i=0;i<nbl;i++){
printf("\n legume %d id =%d ",i+1,b[i].id);
printf("\ le nom %d est = %s",i+1,b[i].name);
}
fclose (fpr);
}

What am I doing wrong with this array in C?

I need to know how many times does "Maria" appears in this array, but when I run it, it says that it appears 51 times, and I think its only like 8
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int g;
int i;
const char * nombres[40] = {"Sandra Marisol","Juan Luis","Perez Luis","Carlitos","Maria","Mariana", "Carlota","Anthony",
"Fernando Jan","Alfonso Roche","Julieta Zacatenco","Maria de los Angeles","Laura Jessica",
"Andrea Maria","Jose Maria","Andres Molina","Aline Derrant","Paquito","Luisa","Ana Maria",
"Caleb","Luis Fernando","Mario Alberto","Paula Monica","Otoniel","Elias Primero","Maurico Enrique",
"Anastasia Maria","Maria Juana","Juana de Arco","Aria Montgomery""Hanna Maria","Magdalena","David Green",
"Florian Drake","Edward Jones","Joakin Broder","Paar","Alicia Torres","Juan Pablo"};
for(i = 0; i>40; i++)
{
printf("%s\n", nombres[40]);
if(nombres[i] == "Maria")
g++;
}
if(g>0){
printf("El nombre de Maria aparece %d veces.", g);
}
else {
printf("El nombre de Maria NO aparece");
}
system("pause");
return 0;
}
if(nombres[i] == "Maria")
You can't compare strings like this. You need to use strstr() to look for substrings in a string.
Also,
printf("%s\n", nombres[40]); probably should have i instead of 40. And your comparison in the middle of your for loop above this is backwards.
And... probably more else wrong, but that is enough for me.
There are lots of error..... Let's see how much I could solve..xd
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int g=0;
int i;
const char * nombres[40] = {"Sandra Marisol","Juan Luis","Perez Luis","Carlitos","Maria","Mariana", "Carlota","Anthony",
"Fernando Jan","Alfonso Roche","Julieta Zacatenco","Maria de los Angeles","Laura Jessica",
"Andrea Maria","Jose Maria","Andres Molina","Aline Derrant","Paquito","Luisa","Ana Maria",
"Caleb","Luis Fernando","Mario Alberto","Paula Monica","Otoniel","Elias Primero","Maurico Enrique",
"Anastasia Maria","Maria Juana","Juana de Arco","Aria Montgomery""Hanna Maria","Magdalena","David Green",
"Florian Drake","Edward Jones","Joakin Broder","Paar","Alicia Torres","Juan Pablo"};
for(i = 0; i<40; i++)
{
printf("%s\n", nombres[i]);
if(!strcmp(nombres[i],"Maria"))
g++;
}
if(g>0){
printf("El nombre de Maria aparece %d veces.", g);
}
else {
printf("El nombre de Maria NO aparece");
}
return 0;
}
Here the counter variable g was not initialized. It should be initialized to 0 otherwize it contains some garbage value.then in for loop the condition was wrong the loop was not being executed because u write I>40 here i is initialized by 0 so condition get false and loop don't run.then printf in the loop contains nombres[40] which gives a nullpointer because you last name is hombres[39].then in if condition you can't just compare string like other variable you have to use lib function which is strcmp which means string compare.
In following conditions
strcmp(s1,s2);
**
*if s1==s2 then it returns 0.
If s1>s2 then it returns 1
If s1<s2 it returns -1
So I wrote !strcmp();
So if string matches it will return 0 and '!' Converts it to 1.
Hope this works.kudos.

Starting with C, struct and function simple program, returned data problably wrong

I'm starting to learn in C and now I'm in the chapters of structs so I'm making a simple program with switch who ask for input from the user if the user press "1" the program ask for data of a new client, and after that you can print it from another function called in a switch case "2", the problem is the printed data is totally wrong I suspect the returned data is wrong or so.
P.D: Exist any way to print only the data introduced before instead 20 times the same data?
Here's the code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct datos{
char nombre[20];
char apellido[20];
char direccion[20];
int edad[3];
long telefono[10];
}agenda;
agenda mostrar_datos();
agenda insercion_datos();
int main(void)
{
char con[3];
int menu;
puts("\n=== Bienvenido a la agenda en C ===\n");
while (!strstr(con,"si"))
{
puts("\n=== Que quieres hacer? ===\n");
fflush(stdin);
puts("\nIntroducir datos [1]\n");
puts("\nVer los datos[2]\n");
puts("\nSalir[3]\n");
scanf(" %d", &menu);
switch(menu)
{
case 1:
insercion_datos();
break;
case 2:
mostrar_datos();
break;
}
}
}
agenda insercion_datos()
{
agenda nuevo_dato;
puts("Bienvenido, vamos a introducir datos.");
puts("Dime su nombre.");
fflush(stdin);
gets(nuevo_dato.nombre);
puts("Dime su apellido.");
fflush(stdin);
gets(nuevo_dato.apellido);
puts("Dime su direccion.");
fflush(stdin);
gets(nuevo_dato.direccion);
puts("Dime su edad.");
fflush(stdin);
scanf(" %d", &nuevo_dato.edad);
puts("Dime su telefono.");
fflush(stdin);
scanf(" %d", &nuevo_dato.telefono);
}
agenda mostrar_datos()
{
int i = 0;
agenda mostrar_dato;
for (i=0;i<10;i++)
{
printf("Nombre: %s\n Apellido: %s\n Direccion: %s\n Edad: %d\n Telefono: %d\n", mostrar_dato.nombre,mostrar_dato.apellido,
mostrar_dato.direccion,mostrar_dato.edad, mostrar_dato.telefono);
}
}
I don't think this will work.
Couple of points to note here:
There is a white space in the scanf statement where you try to read the menu variable in the main()
In your function: insercion_datos() does not do anything besides creating a local variable and filling it with some data.
In your function: mostrar_datos(), the local variable is not initialized, therefore you receive no output.
Try to make a global array of `agenda' and then fill the array of structure everytime you read an input through insercion_datos(). Keep track of the number of inserts you have performed
the when you are printing using the mostrar_datos(), you can use that count and print.
I hope this resolves your doubt as to why there are no returns.

Resources