So what helps me when coding is collaberating everything i've learned into one random project. To better help me and understand when coding. I learnt about getenv a while back and was testing it. Worked fine until I went back to work on learning c and opened the project again...
#include <stdio.h>
#include <strings.h>
#include <windows.h>
#include <stdlib.h>
struct envvariabl3s
{
char *userprofile;
char *systemroot;
};
void loginscreen(void)
{
int testbit = 4000000000;
struct envvariabl3s *envariable;
char *memtes;
printf("\nWelcome to the login screen...\n");
memtes = malloc(20 * sizeof(char));
if(memtes == 0)
{
printf("Error: Not enough memory!");
}
strcpy(memtes, "Herp De Derp");
printf("\nDynamically allocated memory is %s", memtes);
free(memtes);
envariable->userprofile = getenv("USERPROFILE"); //SEGFAULT HERE
envariable->systemroot = getenv("SystemRoot");
printf("\nUserProfile is: %s", envariable->userprofile);
printf("\nSystem Root is: %s", envariable->systemroot);
printf("%d", sizeof(testbit));
}
Envvariable is a pointer to a structure, but you never created a struct for it to point to. It just points to random memory, and assigning into the struct that isn't there causes the crash. You need an actual struct, perhaps allocated using malloc(), for the pointer to point to.
Related
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct bank
{
char *name [3];
char *ha[3];
int bal[3];
};
typedef struct bank bank;
int main()
{
bank *SBI;
SBI=(bank*) malloc(sizeof(bank));
strcpy(SBI->ha[0], "1234");
printf("SUCCESS");
return 0;
}
Why is the above code generating a memory write error? When I run the code it generates some error relating to memory. I am beginner in C programming. Can anyone help me about what is wrong in the code that is causing the error.
You also need to allocate space for your three strings ha[0], ha[1], ha[2]. Your malloc allocates memory for the bank structure, including three pointers, but these pointers need to be allocated too, with malloc or strdup for example:
for (int i = 0; i < 3; i++) {
bank->ha[i] = malloc(MY_STRING_MAXLENGTH);
}
which you later free:
for (int i = 0; i < 3; i++) {
free(bank->ha[i]);
}
free(SBI);
You are copying your string into unallocated memory.
strcpy(SBI->ha[0], "1234")
Use strdup instead of strcpy. Strdup will allocate the memory for you.
I'm curious as to why free(myWord->w) would be an invalid pointer? I allocate memory to it, so shouldn't I free it as well? or does freeing a struct also free all of its fields?
New to C so any insight on the world of pointers is much appreciated!
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct word {
char *w;
} WORD;
void setWord(char **f);
int main() {
WORD *myWord = malloc(sizeof(WORD));
myWord->w = malloc(6);
strcpy(myWord->w, "hello"); // set to "hello"
setWord(&(myWord->w)); // set to "bagel"
free(myWord->w); /* munmap_chunk(): invalid pointer. Aborted (core dumped) */
free(myWord);
return 0;
}
void setWord(char **F) {
*F = "bagel";
}
*F = "bagel"; is not how you assign a string. Instead the code overwrite the value of the pointer myWord->w so when you call free, it's no longer the correct pointer value.
To see that the pointer change, try this:
printf("%p\n", (void*)myWord->w);
setWord(&(myWord->w)); // set to "bagel"
printf("%p\n", (void*)myWord->w);
Consequently, the free call will fail as the pointer-value isn't the one you got from the malloc.
So instead of *F = "bagel"; use
strcpy(*F, "bagel"); // NOT: *F = "bagel"
Further you don't need to pass the address of w. Simply do:
void setWord(char *F) {
strcpy(F, "bagel");
}
and call it like:
setWord(myWord->w);
And...
I allocate memory to it, so shouldn't I free it as well? or does freeing a struct also free all of its fields?
Yes, you must free it.
No, free of a struct does not free members automatically. You must do that.
I am trying to modify a field inside a struct. I have no trouble doing this with other types (i.e. int, float etc.) but char * is giving me problems. I think I have to do something like:
typedef struct{
char *string_field;
} struct_name;
struct_name *struct_name1;
struct_name1 = (struct_name *) malloc(sizeof(struct_name));
strcpy(struct_name1->string_field, new_string);
printf("New string: %s\n", struct_name1->string_field);
But this gives me a segmentation fault. What reason do you think I would get this problem for? Initially, I thought maybe the char *string_field was not big enough to copy to, but I changed the size of it manually to be of size 100 (more than enough) and I still get this problem.
You reserve memory for your struct, which comprises a pointer to a string, but not the space for a string's content. Reserve memory for the string content and let your struct's pointer point to it; then you can copy newstring's content into that memory:
struct_name1->string_field = malloc(strlen(new_string)+1);
strcpy(struct_name1->string_field, new_string);
Allocate memory for the structure as well as for the string.
In example below there is a room for 63 characters in the string.
Remember to free the allocated memory.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char *string_field;
} struct_name;
int main()
{
struct_name *struct_name1;
struct_name1 = malloc(sizeof(struct_name));
struct_name1->string_field = malloc(64*sizeof(char));
strcpy(struct_name1->string_field, "new_string");
printf("New string: %s\n", struct_name1->string_field);
free(struct_name1->string_field);
free(struct_name1);
return 0;
}
OUTPUT:
New string: new_string
im trying to make program that stores person's last name and name in a structure that is dynamically allocated and then prints it in terminal. For now i have got "segmentation fault" error after inputing the last name in terminal. How do i make it work? Thanks in advance!
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person{
char *last_name;
char *name;
};
struct person *p_person;
int main(void)
{
p_person=malloc(sizeof(struct person));
scanf("%s", p_person->last_name);
scanf("%s", p_person->name);
puts(p_person->last_name);
free(p_person);
return 0;
}
p_person->last_name doesn't point to anywhere. You were accessing memory that you are not even permitted to. You invoke undefined behavior accessing it. Solution would be to allocate some memory dynamically or use char last_name[MAXLEN]; in structure.
Solution 1:
struct person{
char last_name[50];
char name[50];
};
Solution 2:
p_person->last_name = malloc(50);
if( p_person->last_name == NULL){
fprintf(stderr,"error in malloc");
exit(1);
}
In the solution-2,
You should do the same thing for name also.
Free the dynamically allocated memory when you are done working with it.
scanf("%49s", p_person->last_name) One less than the buffer size. When scanf() is finished parsing into a string, it appends NUL terminating character automatically.
This program is crashing. Please tell me what's wrong with it. When I use an array instead of a pointer like Name[12] in the structure it doesn't crash. I guess there is some problem in dynamic memory allocation. Help please.
#include <stdio.h>
struct struct_tag
{
int number;
char *Name;
} struct_name;
main()
{
struct_name.number = 34;
char *Name = (char *) malloc(sizeof(char));
strcpy(struct_name.Name,"A");
printf("%d", struct_name.number);
}
You're allocating a single character:
char *Name = (char *) malloc(sizeof(char));
And then never using that memory for anything. You meant to allocate memory for struct_name.Name, undoubtedly. But even if you had done so, you're then filling it with two characters ('a' and '\0'):
strcpy(struct_name.Name,"A");
which will cause an entirely different bug.
You want to say:
struct_name.Name = malloc( 2 );
Since (a) you shouldn't cast the result of malloc() and (b) sizeof(char) is always 1 and (c) you need room for the 0 at the end of your string.
For errors:
You are allocating memeory for *Name however you are not allocating
memory for struct_name.Name. So first thing is you need to allocate memory for struct_name.Name
As you already know that you'll be storing "A" in
struct_name.Name you should allocate memory for 2 char.("A" is string i.e 'A' and '\0')
For warnings:
If you want to use strcpy function include string.h in your code.
Also if you are using malloc include stdlib.h in your code.
Try this fixed code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct struct_tag
{
int number;
char *Name;
}struct_name;
int main()
{
struct_name.number = 34;
struct_name.Name = malloc(sizeof(char)*2); // As you will store "A"
strcpy(struct_name.Name,"A");
printf("%d \t", struct_name.number);
printf("%s \n", struct_name.Name);
return 0;
}
first look code carefully.
char *Name = (char *) malloc(sizeof(char));
strcpy(struct_name.Name,"A");
Hare for what you allocated memory (char *Name) and in which you copied string(struct_name.Name)?
here you not allocate memory for struct_name.Name. Also you have allocate memory for one character and you tried to copy two characters.('A' and '\0').
It should be
struct_name.Name = malloc(2);