i'm having a problem with a little C program i'm making. It's working fine when i compile it and run it on my mac (on a windows 7 partition) and on my work pc (windows 7 too) but i need it to work on a PC that is running a CNC and it is on windows XP. I can change the program location on the two computers, but it won't work anywhere on the windows XP pc It seems to be crashing when it has to write a text file but it's able to overwrite one ... Is there some functions that aren't compatible with windows XP ? I'll try some more and i'll let you know if i come across something.
P.S. can't use the debugguer on this computer because i can't install programs ... (work computer).
Here's the code that's causing a problem :
int WritePrograms(int vitesse, double hauteur, int longueur, int largeur, double localRabotage, double localGroove, int overdrive)
{
char nameOfFile[75];
char nomProgramR[75];
char nomProgramG[75];
char cheminDaccesR[100];
char cheminDaccesG[100];
char cheminDaccesGen[] = "programmes/";
char genR[] = "_Rabotage.nc";
char genG[] = "_Groove.nc";
char confirmation [3];
int i = 0;
int c = 0;
char *nomProgram = NULL;
char *caractere = NULL;
FILE* fichierRabotage = NULL;
FILE* fichierGroove = NULL;
do
{
memset(nomProgramG,0,sizeof(nomProgramG));
memset(nomProgramR,0,sizeof(nomProgramR));
memset(nameOfFile,0,sizeof(nameOfFile));
memset(cheminDaccesG,0,sizeof(cheminDaccesG));
memset(cheminDaccesR,0,sizeof(cheminDaccesR));
do
{
printf("\nVeuillez choisir un nom pour votre programme : ");
nomProgram = Saisie(nameOfFile,60);
}while (nomProgram == "0");
if (strcmp(nomProgram,"exit") == 0)
{
printf("\nVous avez decider de ne pas creer le programme\n\n");
Sleep(2000);
exit(0);
}
else if (strcmp(nomProgram,"\0") == 0)
{
printf("\nVous n'avez pas rentrer de nom pour votre programme\n");
sprintf(nomProgramR,"%dX%.0fX%dX%d_Rabotage.nc",vitesse,hauteur*10000,longueur,largeur);
sprintf(nomProgramG,"%dX%.0fX%dX%d_Groove.nc",vitesse,hauteur*10000,longueur,largeur);
printf("\nUn nom generique lui a ete attribuer\n");
sprintf(nomProgram,"%dX%.0fX%dX%d",vitesse,hauteur*10000,longueur,largeur);
printf("\n%s\n",nomProgram);
strcpy(cheminDaccesR,cheminDaccesGen);
strcpy(cheminDaccesG,cheminDaccesGen);
strcat(cheminDaccesR,nomProgramR);
strcat(cheminDaccesG,nomProgramG);
}
else
{
strcpy(nomProgramG,nomProgram);
strcpy(nomProgramR,nomProgram);
strcpy(cheminDaccesR,cheminDaccesGen);
strcpy(cheminDaccesG,cheminDaccesGen);
strcat(nomProgramR,genR);
strcat(nomProgramG,genG);
strcat(cheminDaccesR,nomProgramR);
strcat(cheminDaccesG,nomProgramG);
}
fichierRabotage = fopen(cheminDaccesR,"r");
fichierGroove = fopen(cheminDaccesG,"r");
if (fichierRabotage != NULL || fichierGroove != NULL)
{
do
{
printf("\nLe fichier existe deja, voulez-vous le remplacez (O/N)?");
caractere = Saisie(confirmation,3);
}while (strcmp(caractere,"O") != 0 && strcmp(caractere,"o") != 0 && strcmp(caractere,"n") != 0 && strcmp(caractere,"N") != 0);
if (strcmp(caractere,"O") == 0 || strcmp(caractere,"o") == 0)
{
c = 1;
}
}
else
{
c = 1;
}
}while (c != 1);
fclose(fichierGroove);
fclose(fichierRabotage);
fichierRabotage = fopen(cheminDaccesR,"w+");
fichierGroove = fopen(cheminDaccesG,"w+");
if (fichierRabotage != NULL && fichierGroove != NULL)
{
}
else
{
printf("\nLe programmme n'as pas pu etre creer\n");
Sleep(2000);
exit(0);
}
fprintf(fichierGroove, "[OUTIL 3-CARBIDE 1/8-TEMPS: 7MIN] \n");
fprintf(fichierGroove, "[MATERIEL-MOUSSE RPM 200]\n");
fprintf(fichierGroove, "G20\nG00\nG90\nT2\nG53 Z\nG53 XY\nG92 Z%.4f\nG4 [Changer l'outil]\nM03\n",localGroove);
fprintf(fichierGroove, "G0 X2.5\nG0 Y2.5\nG0 Z%.4f\n",hauteur);
return 0;
}
and here is headers.h as ask :
#ifndef HEADERS_H_INCLUDED
#define HEADERS_H_INCLUDED
char *Saisie(char *str,int n);
void viderBuffer();
int SaisieNombre(char *chaine,int a);
double SaisieNombreDecimal(char *chaine,int a);
double LireValeurCorrespondante(double thick);
int GetLocals(double *groove, double *rabotage);
int WritePrograms(int vitesse, double hauteur, int longueur, int largeur, double localRabotage, double localGroove, int overdrive);
#endif // HEADERS_H_INCLUDED
The problem here was that by opening two files to check if they existed and if one of them existed. the program would tell me if i wanted to overwrite it. I'd then close both files and overwrite them if needed but if they didn't open, it would try to close a NULL pointer. So the solution was to do this :
if (fichierGroove != NULL)
{
fclose(fichierGroove);
}
if (fichierRabotage != NULL)
{
fclose(fichierRabotage);
}
Lesson here : You can close a NULL pointer in windows 7 but not on XP
Not sure for all other OSes.
Related
I'm new to C, I've already searched and I haven't found an answer, but I've been trying to get the program to give me a list with the name of the products typed in by the user followed by the sum of all prices and I've found the error:
clang-7 -pthread -lm -o main main.c
/tmp/main-7440c0.o: In function `main':
main.c:(.text+0x12b): undefined reference to 'N'
main.c:(.text+0x164): undefined reference to 'Digitanome'
main.c:(.text+0x17f): undefined reference to 'Lista'
clang-7: error: linker command failed with exit code 1 (use -v to see invocation)
exit status 1
The code I've been trying is this one:
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
extern char (N[][40]);
int i;
char p;
int cod,cont, soma2;
char soma[100];
int Digitanome( char [][40], int );
void Lista( char [100][40], int );
typedef struct {
char produto[30];
char seçao [30];
float preco;
int cargo;
}Supermercado;
Supermercado compra;
int main(void)
{
char Nome[100][40] = { '\0' };
int qtdNomes = 0;
soma2 = 0;
do{
printf("\n\nEm qual seção está seu produto?");
printf("\n1-Frutas \n2-Doces \n3-Material de Limpeza\n --> ");
scanf("%d",&cod);
if(cod == 1){
*compra.seçao = *strcpy(compra.seçao,"Frutas");
}
if(cod == 2){
*compra.seçao = *strcpy(compra.seçao, "Doces");
}
if(cod == 3){
*compra.seçao = *strcpy(compra.seçao,"Material de Limpeza");
}
int Digitanome(char N[][40], int i);
{
printf("Informe o produto que você quer nesta seção: \n");
scanf("%s", & *N[i]);
*compra.produto = Digitanome( Nome, qtdNomes );
Lista( Nome, qtdNomes );
return ++i;
}
return 0;
printf("Informe o preço do produto: \n");
scanf("%f", &compra.preco);
soma2 = soma2 + compra.preco;
printf("\nDeseja mais algum produto? \n4-Sim \n0-Não, sair \n --> ");
scanf("%d",&cont);
}while(cont == 4);
{
if (cont == 0)
printf("\nFIM DAS COMPRAS!\n");
void Lista(char p[100][40], int i);{
int j = 0;
for (; j < i; j++ )
printf("\nSeus produtos são:%s\n", compra.produto);
}
printf("Essa compra está custando: %i \n", soma2);
}
}
Can anyone explain to me what is happening and how to solve it?
Several problems:
extern char (N[][40]);
You declare N as extern without initialization so you would also need to delcare it in another module with initialization. But you don't actually ever use the variable N. You have N[][40] as an argument to Digitanome. Once you fix item numbers 2 and 3 below, you can remove extern char (N[][40]); completely.
You define Digitanome and Lista inside main(). You need to define them outside of main().
You have semicolons at the end of Digitanome and Lista function definitions. You need to remove those.
You have code following the return 0 statement.
You call Digitanome from inside Digitanome. That is probably not what you want.
Once you fix those problems, you will probably find more.
As Jim mentioned, there is some syntax error in your code you need to fix.
I could not understand the logic of your code so if you still need help, comment to me so that we can do it together!
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
extern char (N[][40]); int i; char p; int cod,cont, soma2; char soma[100];
int Digitanome( char [][40], int ); void Lista( char [100][40], int ); int qtdNomes = 0;
char Nome[100][40] = { '\0' };
typedef struct { char produto[30]; char seçao [30]; float preco; int cargo; }Supermercado;
Supermercado compra;
int main(void) {
soma2 = 0; do{
printf("\n\nEm qual seção está seu produto?");
printf("\n1-Frutas \n2-Doces \n3-Material de Limpeza\n --> ");
scanf("%d",&cod);
if(cod == 1){
*compra.seçao = *strcpy(compra.seçao,"Frutas");
}
if(cod == 2){
*compra.seçao = *strcpy(compra.seçao, "Doces");
}
if(cod == 3){
*compra.seçao = *strcpy(compra.seçao,"Material de Limpeza");
}
return 0;
printf("Informe o preço do produto: \n");
scanf("%f", &compra.preco);
soma2 = soma2 + compra.preco;
printf("\nDeseja mais algum produto? \n4-Sim \n0-Não, sair \n --> ");
scanf("%d",&cont); }while(cont == 4); {
if (cont == 0)
printf("\nFIM DAS COMPRAS!\n");
printf("Essa compra está custando: %i \n", soma2); } }
int Digitanome(char N[][40], int i)
{
printf("Informe o produto que você quer nesta seção: \n");
scanf("%s", & *N[i]);
*compra.produto = Digitanome( Nome, qtdNomes );
Lista( Nome, qtdNomes );
return ++i;
}
void Lista(char p[100][40], int i) { int j = 0; for (; j < i; j++ )
printf("\nSeus produtos são:%s\n", compra.produto); }
I have this program (school exercise) that simulates a software for managing tests and exercises. Everything works fine... until it doesn't. The second time, in the menu of the program, I want to add an exercise (calling so the function called inserisciEsercizio, "addExercise" in English), the malloc (esercizioPtr newEsercizio = (esercizioPtr)malloc(sizeof (esercizio));) "triggers a breakpoint". I attach the function and where the structs are declared.
What does that mean? How can I resolve it?
Thank you.
I tried looking it up, but I couldn't find anything that could help me understand.
The variables are written in Italian (half in Italian, half in English to be honest). Hope it's not too much of a problem.
struct ListaEsercizi
{
esercizioPtr esercizio;
struct ListaEsercizi *nextListaEsercizi;
};
typedef struct ListaEsercizi listaEsercizi;
typedef listaEsercizi *listaEserciziPtr;
struct Esercizio
{
char titolo[20];
char domanda[40];
char risposte[3][50];
int difficolta;
struct Esercizio *nextEsercizio;
};
typedef struct Esercizio esercizio;
typedef esercizio *esercizioPtr;
void inserisciEsercizio(esercizioPtr *firstEsercizio, autorePtr Autore)
{
listaEserciziPtr newLista = (listaEserciziPtr)malloc(sizeof (listaEsercizi));
esercizioPtr newEsercizio = (esercizioPtr)malloc(sizeof (esercizio)); // <--- here!
//se ne stabiliscono i parametri
if (newEsercizio != NULL)
{
newEsercizio->nextEsercizio = NULL;
printf("Inserisci titolo esercizio ");
scanf_s("%s", newEsercizio->titolo, 20);
printf("Inserisci domanda esercizio: ");
scanf_s("%s", newEsercizio->domanda, 30);
printf("Inserisci difficolta esercizio: ");
scanf_s("%d", &(newEsercizio->difficolta));
for (int i = 0; i < 3; i++)
{
printf(" Scrivere la risposta:\n");
scanf_s("%s", newEsercizio->risposte[i], 100);
}
if (*firstEsercizio == NULL) //caso in cui creo il primo oggetto
{
*firstEsercizio = newEsercizio;
}
else //se non il primo lo inserisco all'interno della lista oggetti
{
newEsercizio->nextEsercizio = *firstEsercizio;
*firstEsercizio = newEsercizio;
}
//mettere malloc
if (newLista != NULL)
{
newLista->nextListaEsercizi = NULL;
newLista->esercizio = newEsercizio;
if (Autore->esercizi == NULL) //caso in cui creo il primo oggetto
{
Autore->esercizi = newLista;
}
else //se non il primo lo inserisco all'interno della lista oggetti
{
newLista->nextListaEsercizi = Autore->esercizi;
Autore->esercizi = newLista;
}
}
else
{
//nel caso malloc restituisca NULL
printf("Memoria non disponibile \n");
}
}
else
{
//nel caso malloc restituisca NULL
printf("Memoria non disponibile \n");
}
}
In you declarations you have:
char risposte[3][50];
And later in the code you have:
scanf_s("%s", newEsercizio->risposte[i], 100);
It allows a 100 chars in a 50 chars array, which probaly leads to memory corruption in the first call to inserisciEsercizio. Using sizeof instead of a constant with scanf_s is usually a good idea:
scanf_s("%s", newEsercizio->risposte[i], sizeof(newEsercizio->risposte[i]));
Still following the saga of a Cobol developer handling C programs on a environment migration.
I think we could manage 90% of the problems so far and most of our C programs are now compiling fine on the RHEL 64 bits.
Friday we found another module that is not compiling and I hope to be the last one.
I am receiving two warnings, but I have no idea about it and our make does not allow us to compile it properly.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <memory.h>
#include <errno.h>
#include </public/prod/src/mfqinc.h>
static FILE *infile = NULL;
static FILE *outfile = NULL;
char inbuf[1024], blockrec[10240];
static char workstring[1024];
static char workstring0[1024];
static char gra2533h [8];
static char gra2401h [8] ;
static char gra2501h [8] ;
static char gra2506h [8] ;
static char crtn[1] ; /* {"0x0A"};*/
int i;
int z;
int f;
int resulisn;
int j;
int d;
int ctrrec;
int nb_ecrit;
static int longueur;
void initworkstring()
{
extern char workstring [1024];
int ik;
for (ik=0; ik < 1024 ;ik++)
{
workstring [ik] = NULL;
}
}
void ecriture()
{
extern char workstring [1024];
extern int longueur;
extern int ctrrec;
nb_ecrit = fwrite(workstring,sizeof(char),longueur,outfile);
ctrrec++;
if ( nb_ecrit != longueur )
{
printf("andlog:erreur d ecriture ");
printf("Ecrit: %i",nb_ecrit);
printf("Erreur no: %i",errno);
exit(60);
}
}
static void errarg(char *errmsg)
{
fprintf(stderr,"ERROR - %s\nCommand format :\n\t",errmsg);
fprintf(stderr," : \n");
/* exit(1); */
}
main (int argc, char *argv[])
{
if ( argc < 3 )
{
printf("<<< Programme : and015 >>>\n");
printf("<<< Nombre de parametres incorrect >>>\n");
printf("<<< Remove catacteres speciaux >>>\n");
printf("<<< Param # 1 = nom du fichier d'input >>>\n");
printf("<<< Param # 2 = nom du fichier d'output >>>\n");
printf("\n");
exit(10);
}
if ((infile = fopen(argv[1],"rb")) == NULL )
{
printf("Erreur sur fichier input \n");
exit(20);
}
if ((outfile = fopen(argv[2],"wb")) == NULL )
{
printf("Erreur sur fichier output \n");
exit(30);
}
initworkstring();
/* remplir les table de catacteres */
crtn[0]=0x0a;
gra2533h[0]=0x1b;
gra2533h[1]=0x5b;
gra2533h[2]=0x32;
gra2533h[3]=0x35;
gra2533h[4]=0x3b;
gra2533h[5]=0x33;
gra2533h[6]=0x33;
gra2533h[7]=0x48;
gra2401h[0]=0x1b;
gra2401h[1]=0x5b;
gra2401h[2]=0x32;
gra2401h[3]=0x34;
gra2401h[4]=0x3b;
gra2401h[5]=0x30;
gra2401h[6]=0x31;
gra2401h[7]=0x48;
gra2501h[0]=0x1b;
gra2501h[1]=0x5b;
gra2501h[2]=0x32;
gra2501h[3]=0x35;
gra2501h[4]=0x3b;
gra2501h[5]=0x30;
gra2501h[6]=0x31;
gra2501h[7]=0x48;
gra2506h[0]=0x1b;
gra2506h[1]=0x5b;
gra2506h[2]=0x32;
gra2506h[3]=0x35;
gra2506h[4]=0x3b;
gra2506h[5]=0x30;
gra2506h[6]=0x36;
gra2506h[7]=0x48;
while (fgets(inbuf,1024,infile) != NULL )
{
i=0;
j=0;
d=0;
for (i=0; i < 1024 ; i++)
{
if ( inbuf [i] == NULL )
{
i = 9999;
}
else
{
if ( inbuf[i] == 0x1b )
{
i++;
d=0;
for (d=0 ;d < 8; d++)
{
if ( inbuf[i] == 0x48 )
{
j= j-d;
workstring[j]=0x0a;
d=99;
}
else
{
if (inbuf[i] == 0x6d)
{
j= j-d;
workstring[j]=0x0a;
d=99;
}
else
{
if (inbuf[i] == 0x53)
{
j=j-d;
workstring[j]=0x0a;
d=99;
}
else
{
workstring[j] = inbuf[i];
j++;
i++;
}
}
}
} /* end du for*/
}/*fin du if 01b*/
else
{
workstring[j] = inbuf[i];
j++;
}
}
/* mettre dans workstring */
workstring [j] = inbuf [i];
}
strcat(workstring,crtn);
longueur = j ;
ecriture ();
initworkstring();
} /* fin du while */
fclose(infile);
fclose(outfile);
exit(0);
}
Those are the warnings I am having.
/exp/prod/src>gcc -m64 mfqlog.c -o mfqlog
mfqlog.c: In function 'initworkstring':
mfqlog.c:48:20: warning: assignment makes integer from pointer without a cast [enabled by default]
workstring [ik] = NULL;
^
mfqlog.c: In function 'main':
mfqlog.c:146:18: warning: comparison between pointer and integer [enabled by default]
if ( inbuf [i] == NULL )
Really sorry to bother with this question. But I really need to compile this code.
The funny fact is that the program is working (probably, for some unknown reason to me, the program was compiling before and it is not anymore due to changes on the compiler maybe?!?) on our actual environment, but if we try to compile it will fail and the only way to make it working is restoring the executable backup.
As we are moving to a new 64 bits environment, it has to be recompiled.
Thank you all for the help.
NULL is defined as (void*)0. Replace NULL with '\0' or 0.
workstring [ik] = '\0';
if ( inbuf [i] == '\0' )
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
I have some troubles when executing my program, some characters appeared out of nowhere ( especially this one : and sometimes others) , I don't understand where is the problem and how to delet them.
Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <magic.h>
#include <string.h>
typedef struct Chaine
{
char * Lachaine;
int Taille_C;
} Chaine ;
char * test ( char*);
void ReccuperationTexte(char** txt);
void afficheTable2D(int** Table, Chaine * Tab_du_texte );
int * Tab_fin( int** Table, Chaine * Tab_du_texte );
char*Le_suff(int* tab_suf,Chaine *);
int ** Table2D ( Chaine *);
char* copietext ( char * , int );
int taille_texte ( char * fichier);
int main (void)
{
system("ls");
Chaine *Tab_du_texte=NULL;
Tab_du_texte=(Chaine*)malloc(sizeof(Chaine));
Tab_du_texte->Lachaine=NULL;
Tab_du_texte->Taille_C=0;
char fichier[50];
char * restest=NULL;
char * LeSuffixe=NULL;
LeSuffixe=(char*)malloc(sizeof(char)*50);
restest=(char*)malloc(sizeof(char)*15);
int **Table=NULL;
int* Tab_final=NULL;
int i;
Tab_final=(int*) malloc (sizeof(int)*100);
printf("tapez le nom du fichier s'il vous plais: ");
scanf(" %s",fichier);
restest=test(fichier);
while(strcmp( restest, "ASCII text") != 0 || strcmp( restest, "rien")==0)
{
printf("il ne s'agit pas d'un fichier texte ou bien le fichier n'existe pas.\nVeillez choisir un autre:");
scanf(" %s",fichier);
restest=test(fichier);
}
printf("vous avez bien selectionné un fichier texte.\n");
Tab_du_texte->Taille_C= taille_texte (fichier);
/*copie du fichier texte dans un tab dynamique*/
Tab_du_texte->Lachaine=(char*)malloc(sizeof(char)*Tab_du_texte->Taille_C);
Tab_du_texte->Lachaine= copietext (fichier, Tab_du_texte->Taille_C);
printf("La chaine est: %s",Tab_du_texte->Lachaine);
fflush(stdin);
/*creation du tableau 2D */
Table=Table2D(Tab_du_texte);
afficheTable2D(Table,Tab_du_texte);
Tab_final=Tab_fin(Table,Tab_du_texte);
for(i=0;i<Tab_du_texte->Taille_C;i++)
printf("%d",Tab_final[i]);
LeSuffixe=Le_suff(Tab_final,Tab_du_texte);
printf("Le suff est:%s",LeSuffixe);
for(i=0; i<Tab_du_texte->Taille_C; i++)
{
free(Table[i]);
}
free(Table);
free(restest);
return 0;
}
char * test ( char* ftest)
{
magic_t cookie;
const char *description;
char *res;
res=(char*)malloc(sizeof(char)*15);
cookie = magic_open(MAGIC_NONE);
if (cookie != NULL)
{
/* on va charger la base de données */
if (magic_load(cookie, NULL) == 0)
{
description = magic_file(cookie, ftest);
if (description != NULL && strlen(description)<15)
strcpy(res,description);
else
{
res="rien";
}
magic_close(cookie);
}
else
fprintf(stderr, "error loading the magic database\n");
}
return res;
}
int taille_texte ( char * fichier)
{
Chaine *Tab_Texte=NULL;
Tab_Texte=(Chaine*)malloc(sizeof(Chaine));
FILE* Texte= NULL;
Texte = fopen(fichier, "r");
fseek(Texte, 0, SEEK_END);
Tab_Texte->Taille_C=ftell(Texte);
return Tab_Texte->Taille_C;
}
char * copietext ( char * fichier, int taille_C)
{
char *Tab_Texte=NULL;
FILE* Texte= NULL;
Texte = fopen(fichier, "r");
fseek(Texte, 0, SEEK_SET);
Tab_Texte=(char*)malloc(sizeof(char)*taille_C);
fread(Tab_Texte,sizeof(char)*(taille_C),1,Texte);
return Tab_Texte;
}
int ** Table2D ( Chaine * Tab_du_texte)
{
int i,j,k,t;
int** Table=NULL;
t=Tab_du_texte->Taille_C;
Table=(int**)malloc(sizeof(int*)*t);
for(j=0;j<t;j++)
Table[j]=(int*)malloc(sizeof(int)*t);
for(j=0; j<t; j++) // Initialisation de la première ligne des i
{
Table[0][j]=0;
}
for(i=1; i<t ;i++)
{
for(k=0; k<i; k++)
{
Table[i][k]=0;
}
for(j=i; j<t; j++)
{
if(((Tab_du_texte->Lachaine[i]>=32 && Tab_du_texte->Lachaine[i]<=126) && (Tab_du_texte->Lachaine[j]>=32 && Tab_du_texte->Lachaine[j]<=126)) && Tab_du_texte->Lachaine[i-1]==Tab_du_texte->Lachaine[j])
{
Table[i][j]=Table[i-1][j-1]+1;
}
else
{
Table[i][j]=0;
}
}
}
return Table;
}
void afficheTable2D(int** Table, Chaine * Tab_du_texte)
{
int i, j,t;
t=Tab_du_texte->Taille_C;
for(i=0; i<t; i++)
{
for(j=0; j<t; j++)
{
if(i>j)
printf(" ");
else
printf("%d",Table[i][j]);
}
printf("\n");
}
printf("\n");
}
int * Tab_fin(int** Table,Chaine * Tab_du_texte)
{
int i,j,t;
t=Tab_du_texte->Taille_C;
int max =0;
int * Tab_suff=NULL;
Tab_suff=(int*)malloc(sizeof(int)*t);
Tab_suff[0]=0;
for (j=0;j<t;j++)
{
for(i=0;i<=j;i++)
{
if (Table[i][j]>max)
max= Table[i][j];
}
Tab_suff[j]=max;
max=0;
}
return Tab_suff;
}
char*Le_suff(int* tab_suf,Chaine * Tab_du_texte)
{
int max,i,max_i,t;
char* suffixe=NULL;
t=Tab_du_texte->Taille_C;
max=0;
for(i=0;i<t;i++)
{
if(max<tab_suf[i])
{
max=tab_suf[i];
}
}
for(i=0;i<t;i++)
{
if(max==tab_suf[i])
max_i=i;
}
suffixe=(char*)malloc(sizeof(char)*max);
strncpy(suffixe,&Tab_du_texte->Lachaine[max_i-(max-1)],max);
printf("\n%s\n",suffixe);
return suffixe;
}
Sorry, the code is not well identified but I will fix it later. ( the program is in french )
Pretty difficult to read french c-code.... Anyway, I would take a second look at the fread in copietext. I don't think that will give you a zero-terminated string.
this code has a strange behavior in the "check_connected" procedure.
The parameter is converted to char [30] before use the strncmp function, if not, the result is "stack overflow". The problem arises in the result of the compare of two strings,
"Le solteria rige el corason.." --> this is the parameter
"La solteria rige el corazon..." --> this is stored in the list
The result is 0. I understand that the strncmp compare all the character of the strings and by common sense the result should not by zero.
#include <string.h>
#include <stdio.h>
#define LONGITUD_USUARIO 30
//estructuras de socorro
typedef struct nodo_list{
char id_usuario[LONGITUD_USUARIO];
struct nodo_list *siguiente;
} nodo;
//definiciones
#define TRUE 1
#define FALSE 0
//variables
nodo *headlist;
int size_var;
//declaracion de metodos
void initialize_list();
int add_connected(char *id_usuario);
int check_connected(char *id_usuario);
int disconnect(char *id_usuario);
int isEmpty();
int size();
//implementacion de metodos
/*
Dado un id usuario lo incorpora al principio de la lista
*/
int add_connected(char *id_usuario){
nodo nuevoNodo;
strcpy(nuevoNodo.id_usuario, id_usuario);
nuevoNodo.siguiente = headlist;
headlist = &nuevoNodo;
size_var++;
return TRUE;
}
int check_connected(char *id_usuario){
nodo *cursor = headlist;
char id_user[LONGITUD_USUARIO];
sprintf(id_user,"%s",id_usuario);
printf(" ----> %d \n",strncmp(cursor->id_usuario, id_user,LONGITUD_USUARIO));
if(!isEmpty()){
while(cursor != NULL && (strncmp(cursor->id_usuario, id_user,LONGITUD_USUARIO) != 0)){
printf(" ----> %d \n",strncmp(cursor->id_usuario, id_user,LONGITUD_USUARIO));
cursor = cursor->siguiente;
}}
return cursor != NULL ;
}
int disconnect(char *id_usuario){
nodo *cursor = headlist, *anterior = NULL;
char id_user[LONGITUD_USUARIO];
sprintf(id_user,"%s",id_usuario);
if(!isEmpty()){
while(cursor != NULL && strncmp(cursor->id_usuario, id_user, LONGITUD_USUARIO) != 0){
anterior = cursor;
cursor = cursor->siguiente;
}
if(anterior == NULL){ // es el primero
headlist = cursor->siguiente;
size_var--;
return TRUE;
}
else
if(cursor != NULL){
anterior->siguiente = cursor->siguiente;
size_var--;
return TRUE;
}
}
return FALSE;
}
void initialize_list(){
headlist = NULL;
size_var = 0;
}
int size(){
return size_var;
}
int isEmpty(){
return size() == 0;
}
void tester_list(){
initialize_list();
printf("Inicializo\n");
if(add_connected("Betina la corbina"))
printf("Agrego a Betina\n");
if(add_connected("CREO EN LA REENCARNACIÓN...(LA UÑA)"))
printf("Agrego a la uña\n");
if(add_connected("La solteria rige el corazon..."))
printf("Agrego a la solteria\n");
printf("ZISE --> %d \n",size());
if(check_connected("Le solteria rige el corason.."))
printf("Cualquiera se mando\n");
if(check_connected("La solteria rige el corazon..."))
printf("verifico correctamente solteria\n");
if(disconnect("La solteria rige el corazon..."))
printf("verifico correctamente solteria\n");
printf("ZISE --> %d \n",size());
if(add_connected("Todos los perros van al cielo..."))
printf("Agrego a perros\n");
printf("ZISE --> %d \n",size());
}
void main(){
tester_list();
}
add_connected sets the global variable headlist to point to the local, automatic variable nuevoNodo. This goes out of scope when the function returns, meaning that behaviour in check_connected and all other functions which access headlist is undefined.
I'm not sure I understand your question but would guess that you're creating a list whose elements all point to the same stack location (used for nuevoNodo in add_connected). If this is happening, note that this behaviour isn't guaranteed.
You want nodes created inside add_connected to remain valid after the function returns so need to allocate memory dynamically:
int add_connected(char *id_usuario){
nodo* nuevoNodo = malloc(sizeof(*nuevoNodo));
if (nuevoNodo == NULL) {
printf("Error - out of memory\n");
return FALSE;
}
strcpy(nuevoNodo->id_usuario, id_usuario);
nuevoNodo->siguiente = headlist;
headlist = nuevoNodo;
size_var++;
return TRUE;
}
At the end of your program, you'll now need to call a new function which calls free for each node in your list.