So I'm getting to know valgrind a bit and I've come across an example that has me confused.
I was shown this code causes a Invalid Write in valgrind:
#include <stdlib.h>
#include <stdlib.h>
int main(int argc, const char* argv[])
{
int index = atoi(argv[1]);
char *x = malloc(10);
x[index] = âfâ;
return 0;
}
while this code causes a segfault in valgrind:
int foo(y)
{
char str[10];
str[11] = âfâ;
return 0
}
So do these examples have anything to do with the fact that example 1 is something thats done on the heap while the 2nd example is done on the stack?
Am I missing something bigger?
Thanks
Related
I'm relatively new to C and cannot figure out why this program seg faults.
It could be a stupid error on my behalf but cannot seem to figure it out.
I also know its unusual using the embedding method I am, but this was down for sheer familiarity with Python3 and the ease of use.
#define PY_SSIZE_T_CLEAN
#define PAM_SM_AUTH
#define PAM_SM_ACCOUNT
//#define PAM_SM_SESSION
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <security/pam_appl.h>
#include <security/pam_modules.h>
#include </usr/include/python3.6m/Python.h>
/* expected hook */
/*
PAM_EXTERN int pam_sm_setcred( pam_handle_t *pamh, int flags, int argc, const char **argv ) {
return PAM_SUCCESS;
}
PAM_EXTERN int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags, int argc, const char **argv) {
printf("Acct mgmt\n");
return PAM_SUCCESS;
}
*/
/* expected hook, this is where custom stuff happens */
PAM_EXTERN int pam_sm_authenticate( pam_handle_t *pamh, int flags,int argc, const char **argv )
{
chdir("../code/facial"); // this changes it to the correct directory to execute
dlopen("/usr/lib/x86_64-linux-gnu/libpython3.6m.so",RTLD_LAZY | RTLD_GLOBAL);
Py_Initialize(); // Starts python interpreter
PyRun_SimpleString("import os\nimport sys\nsys.path.append(os.getcwd())"); // lets python know where we are
PyObject *mymod, *func1, *ret1;
mymod = PyImport_ImportModule("pam_detect"); // This is the .py
if (mymod != 0){ // check if the file file was loaded
func1 = PyObject_GetAttrString(mymod, "detect"); // hel is the function name in the file you declared earlier
ret1 = PyObject_CallObject(func1, NULL); // Null because the function doesnt take an argument.
if (ret1 == 1){
Py_Finalize();
return PAM_SUCCESS;
}
else{
Py_Finalize();
return PAM_AUTH_ERR;
}
}
else{
//printf("Error: can't find file!\n");
return 1;
}
Py_Finalize();
return 0;
}
You have defined the pointers but haven't assigned them to a memory address.
PyObject *mymod, *func1, *ret1;
This line in your code makes a pointer named mymod which can point to a memory containing PyObject, but you haven't given the memory address to it yet.
I don't know if calling the functions will return pointers correctly or not, So when you try to put anything there, it gives segmentation fault if you are trying to assign a variable to a pointer without a memory address.
I can only say this much without knowing where the fault occurred. try putting printf statement before assigning of all 3 pointers and see.
Case 1:
When I take string input, it successfully gives the output, writing this piece of code:
#include <stdio.h>
int main()
{
char *str;
scanf("%s",&str);
printf("%s",&str);
return 0;
}
Case 2:
On the other hand, it throws a Runtime Error for this snippet:
#include <stdio.h>
int main()
{
char *str;
scanf("%s",&str);
printf("%s",str);
return 0;
}
I found this thing peculiar, and want to know why it happens...
Thanks in advance.
None of those two cases are right.
Case 1 only worked because you got lucky, probably by giving a short string as input. Try something like "bfjabfabjkbfjkasjkvasjkvjksbkjafbskjbfakbsjfbjasbfjasbfkjabsjfkbaksbfjasbfkja" and you'll suffer a seg fault, most likely.
You should have a block of memory associated with str, either on the stack by declaring an array for it or on the heap malloc'ing memory for it.
And you shouldn't use the & operator.
So it would go like this:
#include <stdio.h>
int main()
{
char str[50]; // 50 is arbitrary
scanf("%s",str);
printf("%s",str);
return 0;
}
or like this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* str = malloc(50); // 50 is arbitrary
scanf("%s",str);
printf("%s",str);
free(str);
return 0;
}
I want to initialize an array of size 1MB. So my goal is finally write that 1MB to a file.
I am curious every time i use this formula it is giving less than 1mb.
int len = (1048576)/sizeof(int);
data = (int *) malloc(len);
What is correct way ?
Thank you
Edit - As per the comments I have changed the code .
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <string.h>
int main(int argc, char *argv[]) {
int *data;
int bytes = (1024*1024);
data = (int *) malloc(bytes);
for(int i=0;i<bytes;i++){
data[i] = (int)rand();
printf("%d",data[i]);
}
return 0;
}
After compiling it and I tried dumping the data like below
mpicc -o a mpiFileSize.c
./a > dump.dat
Now I see the file size of dump.dat. Why its 2.5MB ?
Try this
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <string.h>
int main(int argc, char *argv[]) {
char *data;
int bytes = (1024*1024);
data = (char *) malloc(bytes);
for(int i=0;i<bytes;i++){
data[i] = (char) rand();
printf("%c",data[i]);
}
return 0;
}
You shoul use character instead of integer.
Although it was already properly answered.
Just a plus to the answer, if one wants to choose the amount of MBs to allocate would make something like:
#include <malloc.h>
#define Mebabyte (1024 * 1024)
int main(int argc, char** argv)
{
void* data = malloc(2 * Megabyte);
// Do your work here...
free(data);
return 0;
}
If you wanted to allocate more than 2 MBs just change the 2.
As already stated before do not use integers as it's going to have more than 1 byte of size. Instead use char or unsigned char. And as stated by another post, there's no need to cast the result of malloc since void* can be turned to a pointer to any type (and in fact it's done implicitly by the compiler).
see: Why does this code segfault on 64-bit architecture but work fine on 32-bit?
If I had this code all inside just one function, I could get everything working fine, but now my problem is that I can't read the results of my regex. When I try printing the first result, I get a segmentation fault. Instead, I was expecting the first regex result to appear of "T/2/b".
Also, the word "Matches" appears on the screen right before the segmentation fault occurred.
Is there something I'm missing?
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <regex.h>
typedef struct{
char str[1000];
} regex;
long regexmatch(const char* str,const char* regexs,size_t nummatch,regex** reg){
regex_t r;regmatch_t match[nummatch];
if (regcomp(&r,regexs,REG_EXTENDED) != 0){return -1;}
if (regexec(&r,str,nummatch,match,0)!=0){regfree(&r);return -1;}
size_t i=0;
for (i=0;i<nummatch;i++){
if (match[i].rm_so > -1){
memset((**reg).str,0,1000);
memcpy((**reg).str,(char*)(str+match[i].rm_so),match[i].rm_eo-match[i].rm_so);
(*reg)++; //this is where I load the result into the struct and advance the pointer.
}
}
char *p=(**reg).str;
*p='\0';
regfree(&r);
return 0;
}
int main(){
char buf[1000];
memset(buf,0,1000);
regex* r=(regex*)buf;
if (regexmatch("T/2/b","([A-Z]+)/([0-9]+)/([a-z]+)",10,&r)==0){
printf("Matches\n");
printf("%s\n",r->str); //causes segmentation fault. Expecting a "T/2/b" to be displayed instead.
}
}
I was trying to mimic strtok functionality but getting segmentation fault. Please help me out here.
Here is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char argv[])
{
int i=0;
char c[]="get the hell out of here";
char *p;
char *temp=(char *)malloc(100);
while(c[i]!='\0')
{
if(c[i]!=' ')
{
*temp=c[i];
temp++;
i++;
}
else
{
*temp='\0';
printf("printing tokenn");
puts(temp);
i++;
temp="";
}
}
return 0;
}
temp="";
This causes temp to point at unmodifiable memory, leading to a fault the next time you try to modify through it. You wanted to restore temp to the value you got from malloc (which you forgot to save).