This function is a part of program which will gain statistics about books (amount of specific letters, words etc.). Thing is that segmentation fault appears when trying to malloc:
*wordArray[arrayIndex] = malloc(sizeof(***wordArray)*(wcslen(newWord)+1));
after reallocing whole array
*wordArray = realloc(*wordArray, (arrayIndex+1)*sizeof(**wordArray));
I know that realloc isn't really efficent but the most important thing at the moment is to understand why it doesn't work at all. Thanks a lot.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#include <wctype.h>
#include <wchar.h>
#define X 2
void wordManager(wchar_t ***, int **, wchar_t *);
int main(int argc, char **argv){
setlocale(LC_ALL, "");
wchar_t **wordArray;
int *wordAmount;
wchar_t word[50];
for(int i=0; i<X; i++){
scanf("%ls", word);
wordManager(&wordArray, &wordAmount, word);
}
for(int i=0; i<X; i++){
printf("%ls; %d times\n", wordArray[i], wordAmount[i]);
}
}
void wordManager(wchar_t ***wordArray, int **wordAmount, wchar_t *newWord){
static int isArrayInitialised = 0;
static int isArrayEmpty = 1;
static int arrayIndex = 0;
int wordLocation;
if(!isArrayInitialised){
*wordArray = malloc(sizeof(**wordArray)*1);
if(*wordArray==NULL){
printf("Error mallocing wordArray");
exit(EXIT_FAILURE);
}
*wordAmount = calloc(1, sizeof(*wordAmount));
if(*wordAmount==NULL){
printf("Error callocing wordAmount");
exit(EXIT_FAILURE);
}
isArrayInitialised = 1;
}
if(isArrayEmpty){
*wordArray[0] = malloc(sizeof(***wordArray)*(wcslen(newWord)+1));
wcscpy(*wordArray[0], newWord);
*wordAmount[0] = 1;
isArrayEmpty = 0;
}
else{
//Check if word is already in an array.
wordLocation = 0;
for(; wordLocation<arrayIndex+1; wordLocation++){
if(!wcscmp(*wordArray[wordLocation], newWord)) break;
}
printf("%d\n", wordLocation);
//Word hasn't been found. Then:
if(wordLocation==arrayIndex+1){
arrayIndex++; //Increase arrays' volume.
*wordArray = realloc(*wordArray, (arrayIndex+1)*sizeof(**wordArray));
if(*wordArray==NULL){
printf("Error reallocating wordArray memory.\n Array index: %d", arrayIndex);
exit(EXIT_FAILURE);
}
*wordAmount = realloc(*wordAmount, (arrayIndex+1)*sizeof(**wordAmount));
if(*wordAmount==NULL){
printf("Error reallocating wordAmount memory.\n Array index: %d", arrayIndex);
exit(EXIT_FAILURE);
}
*wordArray[arrayIndex] = malloc(sizeof(***wordArray)*(wcslen(newWord)+1));
wcscpy(*wordArray[arrayIndex], newWord);
*wordAmount[arrayIndex] = 1;
}
//Word has been found in an array.
else{
(*wordAmount[wordLocation])++;
}
}
}
Related
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.
i'm trying to populate an array of strings in c using dynamic allocation, this is the code snippet
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct test_struct {
char **names;
int age;
} test_struct;
void add_names(char*** array, int number_of_names);
int main() {
test_struct* ts;
char **array;
int number_of_names;
ts = (test_struct*)malloc(sizeof(test_struct));
printf("input the number of names to add: ");
scanf("%d", &number_of_names);
add_names(&array, number_of_names);
printf("%s | %s\n", array[1], array[0]);
return 0;
}
void add_names(char*** array, int number_of_names) {
char *string;
*array = malloc(sizeof(char*)*number_of_names);
for (int i = 0; i < number_of_names; i++){
scanf("%ms", &string);
*array[i] = malloc(sizeof(char)*strlen(string) + 1);
strcpy(*array[i], string);
}
printf("%s | %s\n", *array[0], *array[1]);
}
If I try to populate it with three names I can't get over the second, and if I try to do it with two names the printf statement inside the function prints both names, however the one in the main function prints ( [name1] | (null) )
.
Also if I remove the unnecessary struct part, I have this code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void add_names(char*** array, int number_of_names);
int main() {
char **array;
int number_of_names;
printf("input the number of names to add: ");
scanf("%d", &number_of_names);
add_names(&array, number_of_names);
printf("%s | %s\n", array[1], array[0]);
return 0;
}
void add_names(char*** array, int number_of_names) {
char *string;
*array = malloc(sizeof(char*)*number_of_names);
for (int i = 0; i < number_of_names; i++) {
scanf("%ms", &string);
*array[i] = malloc(sizeof(char)*strlen(string) + 1);
strcpy(*array[i], string);
}
printf("%s | %s\n", *array[0], *array[1]);
}
That doesn't even work with 2 as input. What am I doing wrong here?
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int id;
char* name;
float weight;
} Person;
int main()
{
Person *person=malloc(10*sizeof(Person));
int i=0;
char row[20];
FILE *input=fopen("input.txt","r+");
while(fscanf( input, "%s", &row)>0) i++;
i/=5;
printf("%d\n", i);
fseek(input,0,SEEK_SET);
int j;
char string[20];
for (j=0;j<i;j++){
fscanf(input,"%s",string);
fscanf(input,"ID:%d",&person[j].id);
fscanf(input,"Name:%s",person[j].name);
fscanf(input,"Weight:%f",&person[j].weight);
fscanf(input,"%s",string);
}
fclose(input);
//Person:{
//ID:1214124141
//Name:Trump
//Weight:101.50
//}
//Person:{
//ID:5235252525
//Name:Obama
//Weight:78.30
//}
return 0;
}
Hello!
I want to read a structure from a file, but my array person contains only 0 even after I read from the file. My input file has the structure shown in the comment lines.
What am I not doing well?
Thanks a lot for the help!
fix like this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
long long int id;//32bit int can't hold like 5235252525
char name[20];//Allocate space
float weight;
} Person;
#define FORMAT "%*s ID:%lld Name:%19[^\n] Weight:%f %*s"
int main(void){
FILE *input=fopen("input.txt", "r+");
if(!input){
perror("fopen");
return -1;
}
int n = 0;
Person p;
while(3==fscanf(input, FORMAT, &p.id, p.name, &p.weight))
++n;
printf("number of record: %d\n", n);
Person *person = malloc(n * sizeof(Person));
if(!person){
perror("malloc");
fclose(input);
return -2;
}
rewind(input);
for (int i = 0; i < n; ++i){
fscanf(input, FORMAT, &person[i].id, person[i].name, &person[i].weight);
}
fclose(input);
//check print
for (int i = 0; i < n; ++i){
printf("ID:%lld, Name:%s, Weight:%.2f\n", person[i].id, person[i].name, person[i].weight);
}
free(person);
return 0;
}
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
Can anyone give me some indication as to why array of structs doesn't print out properly ?
I think its something to do with the memory I have allocated to the struct I am unsure !!
Using mac osx mountain lion xcode 4 gcc
Thanks for any help completely stuck!!
(Please have patience I am only a student !)
#include <stdio.h>
#include <limits.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
typedef struct{
char* one;
char* two;
} Node;
Node *nodes;
int count = 0;
//-----------------------------------------------------------------------
void add(char *one,char*two){
char x[40];
char y[40];
printf("reached..\n");
strcpy(x,one);
strcpy(y,two);
printf("--> X: %s\n",x);
printf("--> Y: %s\n",y);
Node newNode;
newNode.one = x;
newNode.two = y;
nodes[count]= newNode;
count++;
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
void print(){
int x;
for (x = 0; x < 10; x++)
{
printf("%d : (%s, %s) \n",x,nodes[x].one, nodes[x].two);
}
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
void check(char **arg)
{
if(strcmp(*arg, "Add") == 0)
{
add(arg[1],arg[2]);
}else if(strcmp(*arg,"print") == 0)
{
print();
}else{
printf("Error syntax Enter either: \n Add [item1][item2]\n OR \n print\n");
}
}
//-----------------------------------------------------------------------
void readandParseInput(char *line,char **arg)
{
if (fgets (line, 512, stdin)!= NULL) {
char * pch;
pch = strtok (line," \n\t");
int count = 0;
arg[0] = pch;
while (pch != NULL)
{
count++;
pch = strtok (NULL, " \n\t");
arg[count] =pch;
}
}else{
printf("\n");
exit(0);
}
}
//-----------------------------------------------------------------------
int main()
{
int size = 100;
nodes = calloc(size, sizeof(Node));
int i;
for(i = 0;i <100; i++){
printf("%s , %s \n",nodes[i].one,nodes[i].two );
// nodes[i].one = ".";
// nodes[i].two = ".";
}
char line[512]; /* the input line */
char *arg[50]; /* the command line argument */
while (1)
{
readandParseInput(line,arg);
if(arg[0] != NULL){
check(arg);
}
}
return(0);
}
You're keeping pointers to the following automatic variables:
char x[40];
char y[40];
These go out of scope when add() returns, leaving you with dangling pointers.
You either have to turn Node::one and Node::two into arrays, or allocate memory for them on the heap.
In you add() function, you cannot assign one struct to another via an = operator... you would have to copy it...
memcpy( &nodes[count], &newNode )
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char *fn;
}NAME;
#define NAME_LEN 20
int main()
{
NAME name;
name.fn = (char *) calloc(NAME_LEN, sizeof(char));
strcpy(name.fn, "Namco");
printf("Name: %s\n", name.fn);
free(name.fn);
return 0;
}
you can't just assign a string like this in c
newNode.one = x;
newNode.two = y;
what is newNode.one referring to???
at Function add
newNode.one = x;
newNode.two = y;
to
newNode.one = strdup(x);
newNode.two = strdup(y);