Basically I'm trying to code a reader for JPEG files (using libjpeg) but I have a segfault, and I wanted to know if someone could see where is my error ? I'm sure it comes from the malloc but I don't know. I tried to put some debug by putting some printf but absolutely NONE of them appear, wtf ?
Thanks for your help mates...
main.c :
#include <stdio.h>
#include <stdlib.h>
#include <jpeglib.h>
#include "fonctions.h"
int main (int argc, char** argv){
int *H;
int *W;
int *C;
printf("COUCOUCOUCOUCOU");
FILE *fichier = NULL;
char car;
fichier = fopen("cara.jpg", "r");
if (fichier == NULL)
printf("Probleme lecture");
lire(fichier, H, W, C);
fclose(fichier);
return 0;
}
lire.c :
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <jpeglib.h>
#include <jerror.h>
unsigned char** lire (FILE* file, int *H, int *W, int *C){
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
int n = 0;
unsigned char** buffer;
printf("SHITSHITSHITSHIT\n");
fflush(stdout);
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo); // Initialisation de la structure
jpeg_stdio_src(&cinfo,file); // file est de type FILE * (descripteur de fichier
// sur le fichier jpega decompresser)
jpeg_read_header(&cinfo,TRUE);// lecture des infos sur l'image jpeg
jpeg_start_decompress(&cinfo);// lancement du processus de decompression
*H = cinfo.output_height;
*W = cinfo.output_width;
*C = cinfo.output_components;
buffer=(unsigned char **)malloc( (*H) *sizeof(unsigned char*) );
while (n < *H)
{
buffer[n] = (unsigned char*) malloc( (*W) * (*C) *sizeof(unsigned char *) );
printf("DEBUG\n");
fflush(stdout);
jpeg_read_scanlines(&cinfo,buffer+n,1); // lecture des n lignes suivantes de l'image
// dans le buffer (de type unsigned char *)
n++;
}
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
return buffer;
}
i compile with :
gcc -c -I/usr/local/include *.c
gcc *.o -o programme -ljpeg
When you call lire, you pass H, W and C to the function. These are pointers and they are not initialized and therefore you get a crash here in lire.
*H = cinfo.output_height;
You need to call the lire function like this:
int H;
int W;
int C;
....
lire(fichier, &H, &W, &C);
Related
I am a beginner learning C.
I am trying to write two functions, one to allocate a string and the other to insert string1 in string2 from position i.
my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
//alocation
char * allouerChaine(int n)
{
char * s =(char*)malloc(n*sizeof(char *));
if(s!=NULL)
return s;
exit(-1);
}
char * strinsert(char *M, char* T ,int i)
{
char * temp=allouerChaine(strlen(M)+strlen(T));
strncpy(temp,M,i);
temp[i]='\0';
strcat(temp,T);
strcat(temp,M+i);
temp[strlen(M)+strlen(T)]='\0';
return temp;
}
int main(){
char *M;
char *T;
char*p;
int i;
printf("faites entre la chaine M: ");
scanf("%s",&M);
printf("\nfaites entre la chaine T: ");
scanf("%s",&T);
printf("faites entrer I: ");
scanf("%d",&i);
p=strinsert(M, T ,i);
printf("%s",p);
return 0;
}
when I try with static strings like :
p=strinsert("hello", "ss" ,2);
printf("%s",p);
the code works, which means I don't have a problem with my functions but I do have a problem inside the main.
i wrote a programe to read integers from a .txt file and put them in an array, it compiles just fine ,but would ask for the number of integers then stops
#include <stdlib.h>
#include <stdio.h>
void genererN ( int n){
int i=0;
FILE* fichier = NULL;
fichier=fopen("valeurs.txt","w");
while (i<n){
fprintf(fichier,"\n%d\n",rand());
i++;
}
}
void replirtab (int **t,int n){
int i=0;int m;
FILE* fichier = NULL;
fichier=fopen("valeurs.txt","r");
char stre[999999] = "";
while(i<n){
fgets(stre, 999999, fichier);
m = atoi(stre);
*t[i]=m;
i++;
}
}
void affichertab (int *t,int n){
int i=0;
while(i<n){
printf("%d\n",t[i]);
i++;
}
}
and this is my main function where i ask for the number of randomly generated integers and use my functions
#include <stdio.h>
#include <stdlib.h>
#include "source1.h"
int main()
{
int n;
printf("donner le nombre de valeurs ");
scanf("%d",&n);
int T[n];
genererN(n);
replirtab(T,n);
affichertab(T,n);
return 0;
}
and the header
#ifndef SOURCE1_H_INCLUDED
#define SOURCE1_H_INCLUDED
void genererN ( int n);
void replirtab (int *t,int n);
void affichertab (int *t,int n);
#endif // SOURCE1_H_INCLUDED
Fix the following problems:
You're not closing the file after you write it, so the buffer isn't being flushed.
You're writing an extra newline before each number, but you don't skip it when reading.
replirtab() expects an array of pointers, but the array contains integers, not pointers. There's no need to indirect through the references. When you pass an array to a function, a pointer to the first element is passed.
#include <stdlib.h>
#include <stdio.h>
void genererN ( int n){
int i=0;
FILE* fichier = NULL;
fichier=fopen("valeurs.txt","w");
if (!fichier) {
printf("Unable to write file\n");
exit(1);
}
while (i<n){
fprintf(fichier,"%d\n",rand());
i++;
}
fclose(fichier);
}
void replirtab (int *t,int n){
int i=0;int m;
FILE* fichier = NULL;
fichier=fopen("valeurs.txt","r");
if (!fichier) {
printf("Unable to read file\n");
exit(1);
}
char stre[999999] = "";
while(i<n){
fgets(stre, 999999, fichier);
m = atoi(stre);
t[i]=m;
i++;
}
fclose(fichier);
}
void affichertab (int *t,int n){
int i=0;
while(i<n){
printf("%d\n",t[i]);
i++;
}
}
I'm trying to write a program that manipulates ppm image files, works fine with relatively small files up to 622x1023 or so, but with a file any bigger the program throws a segfault error.
I have isolated the problem to this function:
void img2list(FILE *fp,int x,int y,int bd,int *resultado,long tamano){
int dimx=x,dimy=y;
int bitDepth=bd;
long numeroPixeles=(dimx*dimy*bitDepth);
int con=0;
int pixels[numeroPixeles];
while (!feof(fp)){
pixels[con]=fgetc(fp);
con++;
}
memcpy(resultado,pixels,tamano);
}
specifically to:
feof(fp)
and
fgetc(fp)
I'm compiling the code with this command:
gcc main.c -o pim
And I'm running Ubuntu 19.04 on a core i7 5820k with 16GB of RAM
Here's the entire code:
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int * getMeta(FILE *fp){
static int meta[3];
size_t len = 0;
char * line = NULL;
char delim[] = " ";
getline(&line,&len,fp);
getline(&line,&len,fp);
char *ptr1 = strtok(line, delim);
char *ptr2 = strtok(NULL, delim);
sscanf(ptr1, "%d", &meta[0]);
sscanf(ptr2, "%d", &meta[1]);
getline(&line,&len,fp);
char *ptr3 = strtok(line, delim);
sscanf(ptr3, "%d", &meta[2]);
return meta;
}
void img2list(FILE *fp,int x,int y,int bd,int *resultado,long tamano){
int dimx=x,dimy=y;
int bitDepth=bd;
long numeroPixeles=(dimx*dimy*bitDepth);
int con=0;
int pixels[numeroPixeles];
while (!feof(fp)){
pixels[con]=fgetc(fp);
con++;
}
memcpy(resultado,pixels,tamano);
}
void list2file(int *pixeles,int x,int y,int bitDepth, char nombre[]){
int dimx = x, dimy = y;
long numeroPixeles = dimx*dimy*bitDepth;
FILE *archivo = fopen(nombre, "wb"); /* b - binary mode */
(void) fprintf(archivo, "P6\n%d %d\n255\n", dimx, dimy);
for(long i=0;i<numeroPixeles;i++){
(void) fprintf(archivo,"%c",(char)pixeles[i]);
}
(void) fprintf(archivo,"\n");
(void) fclose(archivo);
}
int main(void){
int *meta;
int values,dimx,dimy;
int bitDepth=3;
FILE *fp = fopen("test.ppm","rb");
meta=getMeta(fp); // Dimenciones de la imagen
dimx = meta[0];
dimy = meta[1];
values = meta[2];
printf("dimencion en x: %d\n",dimx);
printf("dimencion en y: %d\n",dimy);
printf("cantidad de valores por pixel: %d\n",values);
long tamano=(dimx*dimy*bitDepth*sizeof(int));
int *pixeles=malloc(tamano);
img2list(fp,dimx,dimy,3,pixeles,tamano);
char nombre[]="pena.ppm";
list2file(pixeles,dimx,dimy,bitDepth,nombre);
(void) fclose(fp);
return EXIT_SUCCESS;
}
Thanks.
This:
int pixels[numeroPixeles];
is a stack overflow unless numeroPixeles is bounded by a small constant. Allocating large objects on the stack admits no way to distinguish success/failure; your program just blows up (and possibly yields code execution under the control of whoever authored the data you're processing). To work with arbitrary-size data like this you need malloc where you can check for success.
Good afternoon,
I'm here with a doubt that i am not able to overcome and i've tried a number of ways. I'm doing a program that among other things the user has to enter data about a product where the serial number has to be unique and of type char. What is happening is that when i type the 1st product serial number the program returns that is already a product with this serial number despite being the 1st.
Here's the code I have:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char numeroserie;
char descricao;
float preco;
} stProduto;
/********************** Funcoes dos produtos *************************/
void inserirProduto(stProduto produtos[], int *contadorProdutos);
int procurarNumeroserie(stProduto produtos[], int contadorProdutos, char produtoAProcurar);
int main()
{
stProduto produtos[500];
int contadorProdutos=0;
inserirProduto(produtos,&contadorProdutos);
return 0;
}
void inserirProduto(stProduto produtos[], int *contadorProdutos)
{
char string1;
char posicao;
do
{
printf("Introduza o numero de serie do produto:");
scanf("%s",&string1);
posicao = procurarNumeroserie(produtos,*contadorProdutos, string1);
if (posicao == 0)
{
printf("Ja existe um produto com esse numero de serie!!!\n");
}
}
while(posicao == 0);
strcpy(produtos[*contadorProdutos].numeroserie,string1);
(*contadorProdutos)++;
}
int procurarNumeroserie(stProduto produtos[], int contadorProdutos, char produtoAProcurar)
{
int i;
char posicao;
posicao = 0;
for(i = 0 ; i < contadorProdutos ; i++)
{
if (strcmp(produtos[i].numeroserie, produtoAProcurar) == 0)
{
posicao=i;
i=contadorProdutos;
}
}
return posicao;
}
Someone help please !!I am already getting frustrated.
Thanks
You got it wrong, char is not a string type in c, it's an integer type.
A string is defined as a sequence of bytes non-nul that are followed by a nul byte.
They type char is 1 byte and hence a string can be an array of char, like the following
char string[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
/* ^ nul: it's mandatory
* for this to be a
* string
*/
The code you posted above seems to be Java originally with some fixes to make it compile, but if you enable compilation warnigs the compiler will really piss you off.
You can build a string from an array like I did above, or by using a pointer of char, in that case you need to point to an array or to dynamic memory allocated using malloc().
An example would be
char *hello;
hello = malloc(6);
if (hello == NULL)
return ERROR; /* or whatever is need but do not continue */
strcpy(hello, "Hello");
/* do whatever you want with hello */
free(hello);
I have managed to put i to work:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char numeroserie[9];
char descricao;
float preco;
} stProduto;
/********************** Funcoes dos produtos *************************/
void inserirProduto(stProduto produtos[], int *contadorProdutos);
int procurarNumeroserie(stProduto produtos[], int contadorProdutos, char produtoAProcurar[9]);
int main()
{
stProduto produtos[500];
int contadorProdutos=0;
inserirProduto(produtos,&contadorProdutos);
return 0;
}
void inserirProduto(stProduto produtos[], int *contadorProdutos)
{
char string1[9];
char posicao;
do
{
printf("Introduza o numero de serie do produto:");
scanf("%s",&string1);
posicao = procurarNumeroserie(produtos,*contadorProdutos, string1);
if (posicao == 0)
{
printf("Ja existe um produto com esse numero de serie!!!\n");
}
}
while(posicao == 0);
strcpy(produtos[*contadorProdutos].numeroserie,string1);
(*contadorProdutos)++;
}
int procurarNumeroserie(stProduto produtos[], int contadorProdutos, char produtoAProcurar[9])
{
int i;
char posicao;
posicao = 0;
for(i = 0 ; i < contadorProdutos ; i++)
{
if (strcmp(produtos[i].numeroserie, produtoAProcurar) == 0)
{
posicao=i;
i=contadorProdutos;
}
}
return posicao;
}
Putting numeroserie [8] i assure that the user just insert 8 characters ??
Thanks
I just want to get my vendor ID, i.e. GenuineIntel using cpuid in C.
This is the function I want to use:
void __cpuid(
int cpuInfo[4],
int function_id
);
This is my wrong code:
int main(){
int cpuInfo[4];
__cpuid(cpuInfo, 1);
}
Assuming you are running on Windows, you need to add #include <intrin.h> to your code. See here.
#include <string.h>
#include <locale.h>
#include <intrin.h>
#include <stdio.h>
// Prototipos
int LeeIDFabricante (char * CadFabricante);
//void LeeIDModelo (char * CadenaModelo);
int main(int argc, char *argv[])
{
char CadFabricante[0x20];
char CadenaModelo[0x40];
int Resultado;
setlocale( LC_ALL, "Spanish" );
Resultado = LeeIDFabricante(CadFabricante);
CadFabricante[12]='\0';
printf("\nLa identificacion del fabricante es: %s. El maximo valor de CPUID es %d.\n", CadFabricante, Resultado);
//LeeIDModelo(CadenaModelo);
//printf("\nLa cadena de modelo es: %s\n", CadenaModelo);
printf("\nPulse tecla RETORNO para terminar\n");
getchar();
return 0;
}
int LeeIDFabricante (char *CadFabricante)
{
int p[4] = {-1};
__cpuid(p, 0);
memset(CadFabricante, 0, sizeof(CadFabricante));
*((int*)CadFabricante) = p[1];
*((int*)(CadFabricante+4)) = p[3];
*((int*)(CadFabricante+8)) = p[2];
return p[0];
}