Having trouble with struct pointers - c

I'm having trouble while trying to compile the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Aposta{
char apostador[100];
char time1[100];
char time2[100];
char time3[100];
}Apostas;
typedef struct Jogos{
char time1[100];
int gol1;
char time2[100];
int gol2;
int faltas;
int amarelo;
int vermelho;
}Jogo;
typedef struct Times{
char time[100];
}Time;
typedef struct Tbela{
char time[100];
int pontos;
int ngole;
int ngols;
}Tabela;
Tabela *ptTabela(Time *time, Jogo *jogo, int tamt, int tamj){
int i=0;
Tabela *tabela;
tabela = (Tabela *)malloc((tamt)*(sizeof(Tabela)));
while (i < tamt){
tabela[i].pontos = 0;
tabela[i].ngole = 0;
tabela[i].ngols = 0;
int l;
for (l=0; l < tamj; l++){
if(!(strcmp(time[i].time, jogo[l].time1 ))){
tabela[i].time = jogo[l].time1;
if(jogo[l].gol1 > jogo[l].gol2){
tabela[i].pontos = (tabela[i].pontos + 3);
}
if(jogo[l].gol1 = jogo[l].gol2){
tabela[i].pontos = (tabela[i].pontos + 1);
}
tabela[i].ngole = tabela[i].ngole + jogo[l].gol1;
tabela[i].ngols = tabela[i].ngols + jogo[l].gol2;
}
else if(!(strcmp(time[i].time, jogo[l].time2 ))){
tabela[i].time = jogo[l].time2;
if(jogo[l].gol2 > jogo[l].gol1){
tabela[i].pontos = (tabela[i].pontos + 3);
}
if(jogo[l].gol1 = jogo[l].gol2){
tabela[i].pontos = (tabela[i].pontos + 1);
}
tabela[i].ngole = tabela[i].ngole + jogo[l].gol2;
tabela[i].ngols = tabela[i].ngols + jogo[l].gol1;
}
else{
printf("Time %s not found.", time[i].time);
}
}
}
i++;
}
The compiler says:
I really don't know what is wrong with it, for me, it's just supposed to get the string that is inside jogo[l].time1 and copy it to tabela[i].time. And it looks like they are the exact same type.
I'm using netbeans 7.2 .
Thank you for your patience already. If something is not clear, please, let me know and I will correct it as fast as I can.

You need to do strdup or strcpy or strncpy... - otherwise you make the pointer (which had space allocated to it) point to a new location and that is probably not what you had in mind.

tabela[i].time = jogo[l].time1;
time is a char array. You are trying to assign a string literal to it which is incorrect. You should use strcpy to copy like,
strcpy(tabela[i].time, jogo[l].time1);

Related

Trouble using free() on a char *variable from a struct [duplicate]

This question already has answers here:
How can I correctly assign a new string value?
(4 answers)
Closed 3 months ago.
I am learning C and I have trouble correctly using free() on char *word from my struck. The code works in its currect form but crashes if I uncomment the line in the for loop ant the end of main. How do I free it correctly?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <errno.h>
typedef struct container
{
char *word;
int amount;
} wordContainer;
wordContainer *SetupWordList(int *size, int *lastInit, wordContainer *listIN, bool realloc);
int main(int argc, const char *argv[])
{
wordContainer *listWords = NULL;
int listSize = 10;
int listLastInit = 0;
listWords = SetupWordList(&listSize, &listLastInit, listWords, false);
for (int i = 0; i < listSize/2; i++)
{
fprintf(stdout, "Word: %s | Amount: %i\n", listWords[i].word, listWords[i].amount);
}
for (int i = 0; i < listSize/2; i++)
{
//free(listWords[i].word);
}
free(listWords);
exit(EXIT_SUCCESS);
}
wordContainer *SetupWordList(int *size, int *lastInit, wordContainer *listIN, bool reallocate)
{
if(!reallocate)
{
listIN = (wordContainer *)malloc((*size) * sizeof(wordContainer));
if (listIN == NULL)
{
fprintf(stderr, "Could not allocate enought memory.");
exit(EXIT_FAILURE);
}
}
else
{
listIN = (wordContainer *)realloc(listIN, (*size) * sizeof(wordContainer));
}
for (int i = (*lastInit); i < (*size); i++)
{
listIN[i].word = (char *)malloc(50*sizeof(char));
listIN[i].word = "empty";
listIN[i].word = "cow";
listIN[i].amount = 0;
}
*lastInit = *size;
*size *= 2;
return listIN;
}
I have honestly no idea what is the problem here, everything I could find online sugested that I am maybe using free() multiple times on the same location or that I have overwriten buffers but I don't see how this is the case here.
for (int i = (*lastInit); i < (*size); i++)
{
listIN[i].word = (char *)malloc(50*sizeof(char));
strcpy(listIN[i].word, "empty");
}
Solved my problem. Did not realise that "listIN[i].word = "empty";" makes me lose my mallocated pointer.

C: Segmentation Fault 11 strcpy pointer Array

The code compiles with no errors, but I get a segmentation Fault Error (11), I'm guessing the problem is when I use the strcpy() function in line 82 ,something goes wrong, why im not getting any compile errors and how can I fix it, are the char array pointers well implemented?. I can not modiffy the current structs of the code.
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
typedef struct
{
int n_uea;
char **nombre;
double *calificacion;
} UEA;
typedef struct
{
int n_pais;
char *nombre[50];
} PAIS;
typedef struct
{
char nombre[50];
UEA uea;
PAIS *pais;
} ALUMNO;
void AllocPais(PAIS *p, int np){
p = (PAIS*) malloc(sizeof(PAIS));
p = &p[0];
p->n_pais = np;
for (int i = 0; i < np; i++) {
p->nombre[i] = (char*) malloc(sizeof(char)*50);
}
}
void AllocUEA(UEA *u , int nu){
u->n_uea = nu;
u->nombre = (char **) malloc(sizeof(char*)*nu);
for (int i = 0; i < nu; i++) {
u->nombre[i] =(char*) malloc(sizeof(char)*50);
}
u->calificacion = (double*) malloc(sizeof(double) * nu);
}
void AllocAlumnoMemory(ALUMNO *a, int np, int nu){
AllocPais(a->pais,np);
AllocUEA(&(a->uea),nu);
}
int main(int argc, char const *argv[]) {
ALUMNO* arreglo;
int entradas;
printf("%s\n","Ingrese el numero de Entradas");
scanf("%d",&entradas);
arreglo = malloc(sizeof(ALUMNO)*entradas);
for (int i = 0; i < entradas; i++) {
char separator[10];
char name[20];
int numUea , numPaises;
printf("%s\n","Se espera separador");
scanf("%s",separator);
printf("%s\n","Ingrese el nombre");
scanf("%s",name);
strcpy(arreglo[i].nombre,name);
printf("%s\n","Ingrese el numero de UEA");
scanf("%d",&numUea);
AllocUEA(&arreglo[i].uea,numUea);
for (int a = 0; a < numUea; a++) {
char name [15];
double cal;
scanf("%s %lf", name, &cal);
strcpy(arreglo[i].uea.nombre[a],name);
arreglo[i].uea.calificacion[a] = cal;
}
printf("%s\n","Ingrese Numero de paises");
scanf("%d",&numPaises);
PAIS nuvp;
arreglo[i].pais = &nuvp;
AllocPais(arreglo[i].pais,numPaises);
for (int b = 0; b < numPaises; b++) {
char names [15];
scanf("%s",names);
strcpy(arreglo[i].pais->nombre[b],names);
}
}
return 0;
}
Please note down below points and try them:
Avoid using strcpy/strcat etc. they do not protect against buffer overruns.
Use strlcpy/strlcat instead.
When using strncpy, make sure to NULL terminate the string buffer.

Reallocating pointers to a struct

I'm having an issue understanding this, my code below:
#include <stdio.h>
#include <stdlib.h>
typedef struct mee test;
typedef struct aa fill;
struct aa {
int c;
fill *point;
};
struct mee {
char name;
fill **a;
int b;
};
static fill **store;
static fill *talloc(int tsize);
static int mem;
static int ptr;
static fill *talloc(int tsize)
{ int temp;
temp = ptr;
ptr++;
mem = mem + tsize;
store = realloc(store, mem*sizeof(fill));
store[temp] = malloc(sizeof(fill));
return store[temp];
}
int main() {
test *t;
t = malloc(sizeof(test));
t->a = malloc(sizeof(fill *)*10);
printf("where\n");
for(int i= 0; i < 10; i++) {
t->a[i] = talloc(1);
}
printf("%d\n", store[9]->c); //Problem here
return 0;
}
excuse the terrible names, just some test code for a larger project. This code compiles and runs fine. if I set the code:
printf("%d\n", store[9]->c);
store[0-7] I get 0 as the output, though why does 8-9 give me some gibberish negative number? I'm assuming its a loss it the pointer somewhere.
How can I correct this?
For some background, this is to store pointers to struct in a array so I can free them a lot easier later.

Segmentation error 11 when using struct arrays in c

I am working on a project and have hit a snag that I have spent hours trying to figure out. I'm fairly certain its very close to correct but obviously something is wrong in my malloc of the struct array. I'll post the code below so you can see it. The goal of this function set is to read in movie data saved in a file and put the data into a structure.
#include <stdio.h>
#include <stdlib.h>
#include "support.h"
#include "scanner.h"
#include <string.h>
int counter(char *movierecords)
{
int count = 0;
char *name;
char *about;
int date;
int time;
char *rate;
char *ppl;
char *dir;
//printf("test");
FILE *fp = fopen(movierecords, "r");
//printf("gggg");
name = readString(fp);
while (!feof(fp))
{
//printf("test in loop");
about = readString(fp);
date = readInt(fp);
time = readInt(fp);
rate = readToken(fp);
ppl = readString(fp);
dir = readString(fp);
//printf("test read");
free(name);
free(about);
free(rate);
free(ppl);
free(dir);
//printf("test free");
count++;
name = readString(fp);
}
//printf("test escape loop");
fclose(fp);
//printf("test file close");
return count;
}
movie **readRecord(char *movierecords, int count) //mallocates space and reads data into an array of movie structures
{
int x = 0;
movie **data1;
FILE *fp = fopen(movierecords, "r");
data1 = malloc(sizeof(struct movie *) * (count + 1)); //mallocate space for the struct array movies1
printf("another test");
while (x < count + 1) //loop mallocates space for the string variables in movies1 struct for all movies
{
data1[x]->moviename = malloc(sizeof(char) * 1001);
data1[x]->description = malloc(sizeof(char) * 2001);
data1[x]->rating = malloc(sizeof(char) * 10);
data1[x]->cast = malloc(sizeof(char) * 512);
data1[x]->director = malloc(sizeof(char) * 30);
x++;
}
printf("test point3\n"); x = 0;
while (!feof(fp))
{
data1[x]->moviename = readString(fp);
data1[x]->description = readString(fp);
data1[x]->year = readInt(fp);
data1[x]->length = readInt(fp);
data1[x]->rating = readToken(fp);
data1[x]->cast = readString(fp);
data1[x]->director = readString(fp);
x++;
}
printf("test point4\n");
fclose(fp);
return data1;
}
Header file:
typedef struct entry
{
char *moviename;
char *description;
int year;
int length;
char *rating;
char *cast;
char *director;
} movie;
int counter(char *movierecords);
movie **readRecord(char *movierecords, int count);
Main:
#include <stdio.h>
#include <stdlib.h>
#include "support.h"
#include <string.h>
int main (int argc, char **argv)
{
int count = 0;
printf("%d", argc);
movie **data1;
count = counter(argv[1]);
printf("%d", count);
printf("hello");
data1 = readRecord(argv[1], count);
return 0;
}
You have to allocate memory for this "data1[x]" because your malloc(double pointer) allocate memory for array of your records(single pointer). Fot the single pointer data[x] you have to allocate memory

Function to read in a word into a struct array

I am having an error with the code we are using, was wondering if someone could help debug. Seems like we are getting a malloc error. Thanks.
void readWords(char norm_word[MAXSIZE], Word ** array) {
int i = 0;
bool found = false;
int result = 0;
Word * current_pointer = malloc (sizeof(Word*));//creates a temporary variable for each pointer in the array
for (i=0; i<word_counter; i++) {
current_pointer = *(array+i); //accesses the current pointer
result = strcmp(norm_word, (current_pointer -> word)); //compares the string to each stored string
if (result == 0) {
found = true;
(current_pointer->freq)++;
break;
}
}
if(!found) {
if(pointer_counter == word_counter) {
array = realloc(array, sizeof(array)*2);
pointer_counter*=2;
}
Word * new_pointer = (Word*) malloc (sizeof(Word*));
strcpy(new_pointer -> word, norm_word);
*(array + (pointer_counter - 1)) = new_pointer;
word_counter++;
}
;
}
All pointers have the same size on your system. So a sizeof always returns the same size for any pointer. You want to allocate for the structure, so you need to use sizeof on the name without the star. malloc will return the pointer to that block of memory afterwards.
Here is a short implementation:
#include <iostream>
#include <string>
typedef struct
{
int num;
int numnum;
}numbers;
int main(int argc, char ** argv)
{
numbers* n = (numbers*)malloc(sizeof(numbers));
n->num = 1;
n->numnum = 2;
free(n);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAXSIZE 64
typedef struct word {
char word[MAXSIZE];
int freq;
} Word;
int word_counter = 0;
size_t pointer_counter = 16;//Number of pointers that ensure
void readWords(char norm_word[MAXSIZE], Word ** array) {
int i = 0;
bool found = false;
Word *current_pointer = *array;
for (i=0; i<word_counter; i++) {
if(strcmp(norm_word, current_pointer->word) == 0){
found = true;
current_pointer->freq++;
break;
}
++current_pointer;
}
if(!found) {
if(pointer_counter == word_counter) {
pointer_counter *= 2;
*array = realloc(*array, sizeof(Word)*pointer_counter);
}
Word *new_pointer = *array + word_counter;
new_pointer->freq = 1;
strcpy(new_pointer->word, norm_word);
++word_counter;
}
}
int main(void){
Word *vocabulary = calloc(pointer_counter, sizeof(Word));
char norm_word[MAXSIZE];
while(1==scanf("%s", norm_word)){
readWords(norm_word, &vocabulary);
}
{
int i;
for(i = 0; i < word_counter; ++i){
printf("%s(%d)\n", vocabulary[i].word, vocabulary[i].freq);
}
}
free(vocabulary);
return 0;
}

Resources