I call my program and it is to read a bunch fo integers from the standard input
int main() {
int* s;
derp(s);
return 0;
}
void derp(int *size) {
scanf("%d", size);
}
why is this code causing a segmentation fault?
int* s;
derp(s);
What does s point to? To random garbage memory since its not initialized. You should do this instead:
int s;
derp(&s);
or you could allocate storage space using malloc:
int* s = malloc( sizeof(int) );
derp(s);
free(s);
Because you need to initialize s.
Add this:
s = malloc(sizeof(int));
Remember to free(s) when you're done.
s needs to be initialized using malloc(). As it is now, s points to some random crap somewhere in memory.
Related
I used this code to print some string,but it does not print any thing.What is the problem?
char* getNotFilledEncryptionParams(void)
{
char* nofilledStr;
char tmp[3];
const char * arr[]= {" P,"," Q,"," A,"," B,"," C,"," R,"," S0,","S1,","S2,","F1,","G1"};
for(i=0;i<11;i++)
{
if(filledParams[i] == 0)
{
strcpy(tmp,arr[i]);
strcat(nofilledStr,tmp);
}
}
return nofilledStr;
}
Usage:
int main(void){
char *remaining;
remaining = getNotFilledEncryptionParams();
printf("\r\n Remaining item:%s",remaining);
}
I think the problem is in const char * arr[] and I changed it,but the problem remains.
You didn't allocate any memory for noFilledStr, so its value is indeterminate and strcat(noFilledStr, tmp) is undefined.
Use malloc to allocate memory and initialize noFilledStr with the returned pointer:
char* noFilledStr = malloc(number_of_bytes);
The strings in arr are char[4], not char[3] (do not forget the null byte!). tmp is too small to hold them, so strcpy(tmp, arr[i]) writes out of bounds.
You are trying to build the string to return in the location pointed to by nofilledStr but this pointer is pointing somewhere as you do not initialize it. You could use a sufficiently large static char[] array if you do not have to deal with multiple threads. Otherwise, use malloc() and require the caller to free() the returned string when he is done with it.
I'm writing a C program but i'm getting some memory errors so i decided to make a small program to see when and how to deallocate memory.
My example :
int main() {
char *a=malloc(5);
a="mama";
char *b=malloc(strlen(a));
printf("%s\n",a);
strcpy(b,a);
free(a);
printf("%s\n",b);
return 0;
}
here i'm getting an error :
* Error in `./a': free(): invalid pointer: 0x0000000000400757 *
but when i change just one line :
int main() {
char *a=malloc(5);
strcpy(a,"mama");
char *b=malloc(strlen(a));
printf("%s\n",a);
strcpy(b,a);
free(a);
printf("%s\n",b);
return 0;
}
My second program is working well, so why i'm getting this error in the first?
i hope that you can explain me why.
In My Real program I'm doing like that :
char * getDate(){
char *date=malloc(5);
//some instructions here
return date;
}
int main() {
char *a=malloc(5);//im sure that a will not exceed 5 bytes
a=getDate();
return 0;
}
It's just a small example , and i don't know where to free memory .so how and where i can free memory , have I to free date or the char pointer?
Edited second Time:
void getDate(char *a){
//some instructions here
strcpy(a,"haha");
}
int main() {
char *a=malloc(5);
getDate(a);
int i= strlen(a);
printf("%s and the size is :%d\n",a,i);
free(a);
return 0;
}
what are the rules i have to follow to avoid memory errors.
many thanks.
In the line:
char *a=malloc(5);
You assign a with the address of a dynamically allocated memory block, but then in the line:
a="mama";
You reassign it with the address of the literal string constant "mama". Discarding the pointer to the dynamically allocated block so that when you call
free(a);
a is no longer a valid heap memory block, and cannot be deallocated.
Strings (and arrays in general) in C are not data first-class types and cannot be assigned. You should replace:
a="mama";
with
strcpy( a, "mama" ) ;
The assignment sets the pointer value - it does not copy "mama" to the memory points to by a. The strcpy() call on teh other hand copies the string to the dynamic memory block referenced by a.
In your second code fragment, you are "leaking" the memory allocated in main() since you have reassigned a without freeing the original block. Although in your example you have not free'd a, it remains freeable, because the allocation in GetDate() is dynamic. As a coding style, dynamically allocating memory in a function and returning its pointer is a bad idea since it makes it the responsibility of the caller to know that the memory was dynamically allocated and must be free'd, and it invites memory leaks.
#include<stdio.h>
int main(){
char *q;
int i=0;
do{
*(q+i)=getchar();
i++;
}while(*(q+i)!=48);
int j=0;
for(;j<i;j++)
printf("%c",*(q+j));
}
I try to use in this way. I could compile. However ıt does not work .
My aim is that I wanna acquire char array (unlimited or limit will be defined by the user)
What should I do?
You should read a book on C.
You're just writing into random memory, causing undefined behavior.
You must allocate memory, you can't just write through a non-initialized pointer!
For instance, make it:
char buffer[1024], *q = buffer;
Then make sure you don't overstep inside the loop, of course.
Also, there's no point in writing the access as *(p + i), when p[i] means the exact same thing and is much easier to read.
Finally, remember that technically getchar() returns int, since it can return EOF which is not a character.
1st allocate memory for your pointer *q
include<stdio.h>
int main()
{
int a;
char b[100];
int i=0;
char *p=b;
while((a=getchar())!=EOF)
{
p[i++]=a;
}
p[i+1]='\0';
printf("%s",b);
}
Also you can try heap memory allocation
char *p=(char*)malloc(40);
I have a function that converts decimal to binary and returns a char * of a binary:
void decimal2binary(int decimalNum, int size, char * charPtr){
int decimalTemp = decimalNum;
int modNum;
for(int sizeTemp = size; sizeTemp >= 0; --sizeTemp){
modNum = decimalTemp >> sizeTemp;
if(modNum & 1){
strcat(charPtr, "1");
}else{
strcat(charPtr, "0");
}
}
}
When I try to test it in main, I get the correct out put as and then "Segmentation fault 11" with gcc compiler:
In int main() :
char testArr[] = "test";
char * foo = testArr;
decimal2binary(10,7, foo);
printf("%s\n", foo);
printf("asdasds\n");
Result :
test00001010
asdasds
Segmentation Fault: 11
Any ideas?
The array you pass in has a size of 5 - "test\0".
It doesn't "work" as you are writing in an invalid memory location.
More like undefined behavior.
EDIT:
If you can't tell the size of the buffer to pass in, a suggestion might be to use realloc and grow your array. Return the pointer, but remember to free the allocated memory.
You are getting segmentation fault for attempting to write on memory addresses that are not
inside your memory segment.
Use an array of bigger size or even better use pointers and keep on realloc'ing new space
as needed.
this is just a test code i've been using to figure out how the code works before impelmenting it into my program. basically the same issue happens in both programs, im able to realloc 2 times then it crashes. the final project is a 2d pointer, list length and size lengths. ach of these has to be able to be resized to reasonable limits.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char** tasks;
char buff[1089];
int size, i, list_size=1;
tasks = (char**)malloc(list_size * sizeof(char*));
printf("input a string!\n");
gets(buff);
*tasks[0]=(char*)malloc((strlen(buff)+1));
tasks[0]=buff;
printf("%s\n", tasks[0]);
for (i=1;i<8 ;i++){
list_size++;
printf("%d\n", list_size);
*tasks = realloc(*tasks, list_size* sizeof(char*));
printf("input a string!\n");
gets(buff);
*tasks[i]=(char*)malloc((strlen(buff)+1));
tasks[i]=buff;
printf("%s\n", tasks[i]);
}
free(tasks);
return 0;
}
what am i messing up with here?
Several problems here.
*tasks[0]=(char*)malloc((strlen(buff)+1));
As pointed out by David Heffernan in the comments, you are assigning a pointer to a char. You probably just meant to assign to tasks[0].
tasks[0]=buff;
This is not how you copy a string. You're setting tasks[0] to point to your fixed buffer, and leaking the memory you allocated in the previous step.
*tasks = realloc(*tasks, list_size* sizeof(char*));
This is not a safe way to realloc, and you are also reallocing the wrong pointer (the first entry in the list, rather than the list itself). If the allocation fails, you have lost the original pointer, and leaked that memory. You should realloc to a temporary variable first, like this:
char *temp = realloc(tasks, list_size* sizeof(char*));
if (temp != NULL)
tasks = temp;
And finally, don't cast the result of malloc().