I created a struct and a function that returns that struct.
Afterwards I'm calling that function twice, each time assigned to a different variable.
The problem is that the first variable changes after the second run.
What am I missing here?
code:
struct text_and_len {
char* text;
int len;
};
struct text_and_len get_text_and_length(){
int len;
scanf("%d ", &len);
char text[len];
fgets(text, len+1, stdin);
return (struct text_and_len) {text, len};
}
void get_input_and_check_is_within(){
struct text_and_len b = get_text_and_length();
printf("%s \n", b.text);
struct text_and_len a = get_text_and_length();
printf("%s \n", a.text);
printf("%s \n", b.text);
this will first print the b.text, but then will print the a.text twice.
These lines used in get_text_and_length()():
char text[len];
fgets(text, len+1, stdin);//over writes buffer by at least 1, 2 if wanting a C string. Will cause undefined behavior.(UB)
will potentially allow user to enter input that would over write the buffer.
The code as is also includes variables that reach end of life before they are needed else where, resulting in predictable, but unwanted behavior.
Also the member in the struct char* text; requires memory be allocated before being written to. Thus will also require freeing.
Below is your code refactored to address these, with some other modifications to the prototypes and calling methods that simplify the writing of the code...
struct text_and_len {
char* text;
int len;
};
void get_text_and_length(struct text_and_len *b){
printf("Enter max length of input string\n");
scanf("%d ", &(b->len));
//b->text[b->len];//VLA, but has already been declared as char *
b->text = malloc(b->len + 2);//room for NULL terminator AND newline
memset(b->text, 0, b->len+2);//zero variable to all NULL
//fgets(text, len+1, stdin);//text has no memory
//and as is would have over-written
//buffer - UB
printf("Enter string no longer than max length\n");
fgets(b->text, b->len+2, stdin);//note len+2 provides room
//for len char + NULL + newline
}
void get_input_and_check_is_within(struct text_and_len *b){
get_text_and_length(b);
printf("max length: %d \n", b->len);
printf("text entered:%s \n", b->text);
}
int main(void)
{
struct text_and_len a = {0};
get_input_and_check_is_within(&a);
free(a.text);//allocated in get_text_and_length()
return 0;
}
Hello guys i just want to read the students from a file and then ask the user to add a new student but first I have to add it to my structur and I don't really kmow how to edite or add students to my allocated structure. Please learn me how to send the values of my struct to any other function and edite them..
struct student {
char personnummer[11];
char förnamn[11];
char efternamn[10];
char gender[7];
char programmdife[20];
char age[4];
char email[30];
//struct likaprogramms *likaprogramm;
} *personer;
void f(struct student **x)
{
char str[200];
int j=0;
struct student *personer = (struct student*)malloc(j * sizeof(struct student));
FILE* f;
f = fopen("elever.txt", "r");
while (fgets(str,sizeof str, f)!=NULL )
{
sscanf(str,"%10s %9s %9s %6s %19s %3s %29s", personer[j].personnummer,personer[j].förnamn, personer[j].efternamn, personer[j].gender, personer[j].programmdife, personer[j].age, personer[j].email);
printf("%10s %9s %9s %6s %19s %3s %29s\n", personer[j].personnummer,personer[j].förnamn, personer[j].efternamn, personer[j].gender, personer[j].programmdife, personer[j].age, personer[j].email);
j++;
*x=personer;
}
fclose(f);
//free(personer);
}
int i;
int main()
{
getchar();
printf("skriv ny personnummret\n");
getchar();
fgets(personer->personnummer,11,stdin);
printf("skriv förnamn\n");
getchar();
fgets(personer->förnamn,50,stdin);
printf("skriv gender\n");
fgets(personer->gender,20,stdin);
printf("skriv programm\n");
fgets(personer->programmdife,50,stdin);
printf("skriv ålder\n");
getchar();
fgets(personer->age,4,stdin);
printf("skriv email\n");
getchar();
fgets(personer->email,40,stdin);
// printf("%s %s %s %s %s %s %s", personnummer,förnamn,efternamn,gender,programm,age,email);
return 0;
}
As already stated in the comments your malloc will return either NULL or a valid pointer to a buffer of 0 bytes, because j is 0 when malloc is called.
No matter which happens, your code will write to invalid memory.
Then i would strongly recommend to enable warnings (gcc/clang: -W -Wall -Wextra).
One possible solution would be to set *x = NULL at the start of your function and use realloc to increase the buffer blockwise in the while loop.
In this case the caller has to make sure to use free on the memory if it is not used anymore.
Something like this:
const int block_size = 16;
int num_allocated = 0;
*x = NULL;
while (your_condition)
{
if (num_allocated <= j)
{
struct student *new_ptr = realloc(*x, (sizeof(struct student) * num_allocated) + (sizeof(struct student) * block_size));
if (new_ptr == NULL)
{
// realloc failed, but ptr is still valid (or NULL if the first call to realloc failed)
return num_allocated;
}
*x = new_ptr;
num_allocated += block_size;
}
// use *x as array of struct student here and fill it
// for every filled element j has to be increased
}
return number of (usable) elements
You can adjust the blocksize for your needs.
If you do not want to waste memory you can also shrink the buffer at the end to the really needed size:
struct student *new_ptr = realloc(*x, sizeof(struct student) * num_allocated);
if (new_ptr == NULL)
return j;
*x = new_ptr;
return j;
I am about to create a programm which stores data of students in a list.
My question is, how to shall I allocate memory for each char string in my struct array.
My code is down below. If there're some other mistakes, please correct me.
#include <stdio.h>
#include <stdlib.h>
#define DATA 10;
#define NAME 10;
typedef struct{
int id;
char *givenname;
char *familyname;
} students;
int main()
{
int answer;
int incr = 0; // Index for students in the list
int datalen = DATA;
int namelen = NAME;
students *studentlist;
studentlist = malloc(datalen * sizeof(students)); // Allocate memory for first ten students
if(NULL == studentlist){
printf("Error: Couldn't allocate memory\n");
exit(0);
}
for(incr = 0; incr < datalen; incr ++){
printf("Add student to the list? Yes(1) No(2)\n");
scanf("%d", &answer);
if(answer != 1){
break;
}
studentlist[incr]->givenname = malloc(namelen * sizeof(char)); // Allocate memory for each name
studentlist[incr]->familyname = malloc(namelen * sizeof(char));
printf("Insert ID: ");
scanf("%d", &studentlist[incr].id);
printf("Insert given name: \n");
scanf("%s", studentlist[incr].givenname);
printf("Insert family name: \n");
scanf("%s", studentlist[incr].familyname);
}
free(studentlist);
free(studentlist.givename);
free(studentlist.familyname);
return 0;
}
Reference of some elements is wrong:
studentlist[incr]->givenname
It should be:
studentlist[incr].givenname
Allocation of strings seems fine.
Your freeing code needs change:
free(studentlist);
free(studentlist.givename);
free(studentlist.familyname);
You need to free studentlist.givename and studentlist.familyname in a loop and then free studentlist at the end:
for(incr = 0; incr < datalen; incr ++){
free(studentlist[incr].givename);
free(studentlist[incr].familyname);
}
free(studentlist);
I need help solving the code below. After the code is compiled using gcc it can be run like ./compiledFile inputFile.txt It should take the inputFile.txt read it while allocating memory dynamically for each variable in this case name and courseID, but my code is not working. The place that I don't understand the most and need help is allocating memory, inserting data into structures and printing the data like the example given below. By the look of this code you could tell that I am a newbie to c and dynamic memory allocation and structure in all.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct people
{
char* name[10];
char* courseID[15];
int grade;
};
void printData(struct people student[], int count);
int main(int argc, char* argv[])
{
FILE *in_file;
char buffer[30];
char *token, *del=",";
int count=0;
struct people student[20];
if(( in_file = fopen(argv[1], "r")) == NULL)
{
printf("unable to open the file");
}
while (fgets(buffer, sizeof(buffer), in_file))
{
student = malloc(sizeof(struct people));
token = strtok(buffer, del);
strcpy(student[count].name, token);
count++;
}
fclose(in_file);
printData(student, count);
}
void printData(struct people student[], int count)
{
int i;
for(i=0; i<count; i++)
{
printf("%s", student[i].courseID);
if (strcmp((student[i].name, student[i].courseID) > 0))
{
printf("%s %s", student[i].name, student[i].grade)
}
}
}
the data.txt file has the following content separated by a comman:
John,MATH 1324,90
David,SCI 1401,88
Omondi,MATH 1324,89
David,MATH 1324,90
when printed out it should look like the following:
MATH 1324
John 90
Omondi 89
David 90
SCI 1401
David 88
first of all, it would be great if you could also share what is the actual output or error you get while running this program.
most of the time dynamic memory allocation is used when we do not know the actual size of data elements, but here you have already fixed the size of struct people student as 20
struct people student[20];
this is absolutely fine, but then you do malloc in while loop
student = malloc(sizeof(struct student);
you have already alloted 20 locations using array declaration, now malloc is not required.
if you want to use dynamic memory allocation using pointers for learning purpose then you should first declare student as pointer to type struct people
struct people* student;
allocate memory dynamically in while loop
student=(struct people*) malloc(sizeof(struct people));
then access it
*(student+count)
hope this helps, if you still have doubts/problems edit the question and include the output/error you get while compiling/running this program.
Several issues with the Question code...
1) Definition of main():
int main(int argc, char* argv[])
It must return an integer. Add a return statement at the end of main(), and make a proper "CLEANUP" section:
printData(student, count);
CLEANUP:
if(in_file)
fclose(in_file);
return(0);
}
2) Better handling of fopen() error condition:
if(( in_file = fopen(argv[1], "r")) == NULL)
{
printf("unable to open the file");
goto CLEANUP;
}
And, initialize the in_file pointer:
int main(int argc, char* argv[])
{
FILE *in_file = NULL;
3) Next, the exact definition of student needs to be established. Is it a static array, or is a pointer to a dynamically allocated array? I will assume that you would like to use a dynamic array (given the question text). However, this assumption conflicts with the following line, which defines student as a static array:
struct people student[20];
Change it to:
struct people *student = NULL;
4) Now, the following question code allocates a new (separate) chunk of memory for each student:
student = malloc(sizeof(struct people));
However, what is needed is all the student records in one array, in the same chunk of memory. So, what is needed is to expand a chunk of memory to include student records as they are read, like this:
while (fgets(buffer, sizeof(buffer), in_file))
{
void *tmp = realloc(student, sizeof(struct people) * (count + 1));
if(NULL == tmp)
{
printf("realloc() failed.\n");
goto CLEANUP;
}
student = tmp;
token = strtok(buffer, del);
5) Take a look at the people structure:
struct people
{
char* name[10];
char* courseID[15];
int grade;
};
It appears that the question code has some difficulty when it comes to pointers & arrays. The code is attempting to define the name and courseID fields as both pointers, and arrays. Given that the question is to do with dynamically allocating stuff, I elect to go that direction. Hence, this structure should be changed to the following:
struct people
{
char *name;
char *courseID;
int grade;
};
6) So, each time through the loop, the student name will be placed in allocated storage, and pointed to by the .name field. So, change this:
token = strtok(buffer, del);
strcpy(student[count]->name, token);
count++;
}
to this:
token = strtok(buffer, del);
student[count].name = strdup(token);
count++;
}
7) I don't understand the intent of this line:
if (strcmp((student[i].name, student[i].courseID) > 0))
I am inclined to eliminate it.
8) The following line has flaws:
printf("%s %s", student[i].name, student[i].grade)
Change it to this to print the integer grade (and don't forget the ending semicolon):
printf("%s %d\n", student[i].name, student[i].grade);
The '\n' makes the output look better, one record per line.
9) Since student is a pointer to dynamically allocated memory (not a static array), change this:
void printData(struct people student[], int count)
to this:
void printData(struct people *student, int count)
10) Now, finish the task of parsing the data; from this:
token = strtok(buffer, del);
strcpy(student[count].name, token);
count++;
}
to this:
token = strtok(buffer, del);
student[count].name = strdup(token);
token = strtok(NULL, del);
student[count].courseID = strdup(token);
token = strtok(NULL, del);
student[count].grade = strtol(token, NULL, 10);
count++;
}
11) Now, to make life easier, sort the array. First by courseID, then by name:
...
count++;
}
/** Sort the array by coursID, then by name. **/
qsort(student, count, sizeof(*student), CmpStudentRecs);
printData(student, count);
...
Which will require an additional "Compare Student Recs" function:
int CmpStudentRecs(const void *recA, const void *recB)
{
int result = 0;
struct people *stuRecA = (struct people *)recA;
struct people *stuRecB = (struct people *)recB;
/** First compare the courseIDs **/
result=strcmp(stuRecA->courseID, stuRecB->courseID);
/** Second (if courseIDs match) compare the names **/
if(!result)
result=strcmp(stuRecA->name, stuRecB->name);
return(result);
}
12) Some finishing touches with the printData() function:
void printData(struct people *student, int count)
{
int i;
char *courseID = "";
for(i=0; i<count; i++)
{
if(strcmp(courseID, student[i].courseID))
{
printf("%s\n", student[i].courseID);
courseID = student[i].courseID;
}
printf("\t%s %d\n", student[i].name, student[i].grade);
}
}
Finished. Output:
SLES11SP2:~/SO> ./test data.txt
MATH 1324
David 90
John 90
Omondi 89
SCI 1401
David 88
SLES11SP2:~/SO>
SPOILER
Change the definition of people to:
struct people
{
char name[10];
char courseID[15];
int grade;
};
This assumes that name won't be longer than 9 characters and coursID won't be longer than 14 characters. If that is not true, change them accordingly.
The line:
student = malloc(sizeof(struct student);
is wrong in couple of ways.
student is already declared to be an array of people. You cannot assign it to point to memory allocated by malloc.
struct student is not a type.
That line can be removed.
The line
strcpy(student[count].name, token);
can cause problems if the length of token is longer than 10 (or whatever size you choose for name in people). The safer thing to do is use strncpy.
strncpy(student[count].name, token, 10);
student[count].name[9] = '\0';
You have not set the value of courseID anywhere. Yet, you are trying to print it in printData. You are doing the same thing for grade. You need to update the processing of input lines to set those correctly.
Change the while loop to:
while (fgets(buffer, sizeof(buffer), in_file))
{
token = strtok(buffer, del);
strncpy(student[count].name, token, 10);
student[count].name[9] = '\0';
token = strtok(NULL, del);
strncpy(student[count].courseID, token, 15);
student[count].courseID[14] = '\0';
token = strtok(NULL, del);
student[count].grade = atoi(token);
count++;
}
There are couple of syntax errors in printData. However, fixing those syntax errors does not take care of your printing requirements. It will be easier to print the data in the order that you want to if you sort the data. The following functions will help you sort the data.
int compareStudent(const void* ptr1, const void* ptr2)
{
struct people* p1 = (struct people*)ptr1;
struct people* p2 = (struct people*)ptr2;
return (strcmp(p1->courseID, p2->courseID));
}
void sortData(struct people student[], int count)
{
qsort(student, count, sizeof(struct people), compareStudent);
}
You can call sortData before calling printData or call sortData first in printData. The logic for printing the data needs to be updated a little bit. Here's an updated printData.
void printData(struct people student[], int count)
{
int i;
int j;
sortData(student, count);
for(i=0; i<count; ++i)
{
printf("%s\n", student[i].courseID);
printf("%s %d\n", student[i].name, student[i].grade);
for ( j = i+1; j < count; ++j )
{
if (strcmp(student[i].courseID, student[j].courseID) == 0)
{
printf("%s %d\n", student[j].name, student[j].grade);
}
else
{
i = j-1;
break;
}
}
}
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct people {
char name[10];//char *name[10] is array of pointer
char courseID[15];
int grade;
};
void printData(struct people student[], int count);
int main(int argc, char* argv[]){
FILE *in_file;
char buffer[30];
char *token, *del=",";
int count=0;
struct people student[20];
if((in_file = fopen(argv[1], "r")) == NULL){
printf("unable to open the file");
return -1;//It is not possible to continue the process
}
while (fgets(buffer, sizeof(buffer), in_file)){
//student = malloc(sizeof(struct people));//It is by securing an array already
token = strtok(buffer, del);
strcpy(student[count].name, token);
token = strtok(NULL, del);
strcpy(student[count].courseID, token);
token = strtok(NULL, del);
student[count].grade = atoi(token);
count++;
}
fclose(in_file);
printData(student, count);
}
int cmp(const void *a, const void *b){
const char *x = ((const struct people*)a)->courseID;
const char *y = ((const struct people*)b)->courseID;
return strcmp(x, y);
}
void printData(struct people student[], int count){
qsort(student, count, sizeof(struct people), cmp);//sort by courseID
char *prev = "";
int i;
for(i=0; i<count; i++){
if(strcmp(prev, student[i].courseID)!=0){
prev = student[i].courseID;
printf("\n%s\n", prev);
}
printf("%-9s %d\n", student[i].name, student[i].grade);
}
}
When the user enters information for a friend, I want the pointer to allocated appropriate space and the friend information be stored in this allocated space. i've read snippits other places that mention using a buffer array as an argument to scanf, but I'm just having a putting this all together. Here is what I have so far.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
//Structure for contacts
typedef struct friends_contact{
char *First_Name;
char *Last_Name;
char *home;
char *cell;
}fr;
void menu(fr*friends ,int* counter,int user_entry,int i);
void setFirst(fr*,int *,int i);
char getFirst(fr*,int i);
void add_contact(fr*friends,int* counter,int i);
void print_contact(fr*friends ,int* counter, int i);
int main()
{
int user_entry=0;
fr friends[5];
int buffer[50];
int counter=0;
int i=0;
for(i=0;i<5;i++)
{
friends[i].First_Name = (char*) malloc(sizeof(char) * 64);
free(friends[i].First_Name);
}
menu(friends, &counter,user_entry,i);
getch();
return 0;
}
//Menu function
void menu(fr*friends,int* counter,int user_entry, int i)
{
do{
int result;
printf("\nPhone Book Application\n");
printf("1) Add friend\n2) Delete friend\n3) Show a friend\n4)"
"Showonebook\n5)Exit\n");
scanf("%d", &user_entry);
if(user_entry==1)
{
add_contact(friends,counter,i);
}
if(user_entry==2)
{
}
if(user_entry==3)
{
}
if(user_entry==4)
{
print_contact(friends, counter,i);
}
}while(user_entry!=5);
}
void setFirst(fr*friends, int* counter, int i)
{
//malloc issue **
friends=(fr*) malloc(sizeof(fr));
printf("Enter a first name \n");
scanf("%s",friends[*counter].First_Name);
}
char getFirst(fr*friends , int pos)
{
printf("%s ", friends[pos].First_Name);
return *friends[pos].First_Name;
}
void add_contact(fr*friends,int* counter,int i)
{
setFirst(friends,counter,i);
(*counter)++;
}
void print_contact(fr*friends ,int* counter, int i)
{
for( i = 0; i < *counter; i++)
if (strlen(friends[i].First_Name))
{
getFirst(friends, i);
}
}
This is only part of the code obviously, and as of right now I get a segmentation fault after I enter a name into the add name function. It loops to the menu one last time before quitting. I realize that I have gone wrong somewhere, and I would like to try and fix this with the buffer solution. Solutions anyone?
Your fr variable is a pointer to some location on the stack that's already got space allocated. You shouldn't be using that - it's already initialized and you can't malloc it (or at least you never ever should). You should instead pass a pointer and initialize it.
That is to say:
fr *friends;
And then when you want to allocate space
friends = (fr*) malloc(sizeof(fr)* NUMBER OF FR YOU WANT);
Furthermore, you need to initialize the elements of your structure if you want to use them, since they're all pointers. This would be done similarly
friends[i].First_Name = (char*) malloc(sizeof(char)* (LENGTH OF STRING + 1));
Or it would be friends[i]->First_Name depending on how you've sent it along to your function.
A good solution for you would just be to initialize the members of the struct inide your main
int i;
fr friends[5];
for(i=0;i<5;i++)
{
friends[i].First_Name = (char*) malloc(sizeof(char) * 64);
friends[i].Last_Name = (char*) malloc(sizeof(char) * 64);
friends[i].home = (char*) malloc(sizeof(char) * 64);
friends[i].cell = (char*) malloc(sizeof(char) * 64);
}
//
//Do functions (without malloc'ing)
//
for(i=0;i<5;i++)
{
free(friends[i].First_Name);
free(friends[i].Last_Name);
free(friends[i].home);
free(friends[i].cell);
}
Here I've chosen 64 to be the length of string. You can set it to whatever you think works.
The bottom line is that you have to allocate space for a pointer before you can use it. Otherwise it's not pointing to any memory you can use and you'll get a segmentation fault. Also, don't forget to free once you're done with the memory you've allocated. Do remember that you can't use it once you've freed it (unless you malloc it again).