The code I am implementing in which I split the command first by pipes then by spaces.
int main(){
pid_t pid;
while (1) {
printf("$ ");
char *cmd;
ssize_t size=0;
getline(&cmd,&size,stdin);
if (cmd[strlen(cmd)-1]== '\n') {cmd[strlen(cmd)-1]='\0';}
char** commands = splitter(cmd,"|");
int i=0;
int fd[2],in=0;
while (commands[i+1]!=NULL){
pipe(fd);
char **args = splitter(commands[i]," \t");
pid = fork();
if (pid==-1) {exit(EXIT_FAILURE);}
else if (pid==0){
close(fd[0]);
changeIO(in,0);
changeIO(fd[1],1);
execvp(args[0],args);
}
else{
waitpid(pid,NULL,0);
close(fd[1]);
close(in);
in = fd[0];
}
i++;
}
char **args = splitter(commands[i+1]," \t");
changeIO(in,0);
execvp(args[0],args);
}
}
Here follows the implementation of the functions the code above uses
void changeIO(int oldfd,int newfd){
if (oldfd!=newfd){
dup2(oldfd,newfd);
close(oldfd);
}
}
char** splitter(char* stringToSplit, char* delimiter){
char *token;
int initial_size = 300;
char** args = malloc(initial_size*sizeof(char*));
token = strtok(stringToSplit,delimiter);
int index = 0;
while (token != NULL) {
args[index] = token;
index++;
if (index >= initial_size) {
initial_size = initial_size + 100;
args = realloc(args,initial_size*sizeof(char*));
if (!args) exit(EXIT_FAILURE);
}
token = strtok(NULL,delimiter);
}
args[index] = NULL;
return args;
}
Ok executing the code I get a segmentation fault when I enter the command in the user input. Testing various options I came to realize it has something to do with the char** args in which I pass the tokens of each commands. I can't understand why this happens since memory is allocated and from what I understand I just point the pointer args to that allocated memory. Any help appreciated.
EDIT: Checked with valgrind. Results below:
==3361== Memcheck, a memory error detector
==3361== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==3361== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==3361== Command: ./mysh3
==3361==
==3361== Conditional jump or move depends on uninitialised value(s)
==3361== at 0x40AFE97: getdelim (iogetdelim.c:59)
==3361== by 0x40ACDD1: getline (getline.c:32)
==3361== by 0x80486C4: main (in /home/dimitris/Desktop/mysh3)
==3361==
$ ls
==3361== Invalid read of size 1
==3361== at 0x4101CAA: execvpe (execvpe.c:50)
==3361== by 0x4101B33: execvp (execvp.c:26)
==3361== by 0x804885F: main (in /home/dimitris/Desktop/mysh3)
==3361== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==3361==
==3361==
==3361== Process terminating with default action of signal 11 (SIGSEGV)
==3361== Access not within mapped region at address 0x0
==3361== at 0x4101CAA: execvpe (execvpe.c:50)
==3361== by 0x4101B33: execvp (execvp.c:26)
==3361== by 0x804885F: main (in /home/dimitris/Desktop/mysh3)
==3361== If you believe this happened as a result of a stack
==3361== overflow in your program's main thread (unlikely but
==3361== possible), you can try to increase the size of the
==3361== main thread stack using the --main-stacksize= flag.
==3361== The main thread stack size used in this run was 8388608.
==3361==
==3361== HEAP SUMMARY:
==3361== in use at exit: 2,520 bytes in 3 blocks
==3361== total heap usage: 5 allocs, 2 frees, 4,568 bytes allocated
==3361==
==3361== LEAK SUMMARY:
==3361== definitely lost: 0 bytes in 0 blocks
==3361== indirectly lost: 0 bytes in 0 blocks
==3361== possibly lost: 0 bytes in 0 blocks
==3361== still reachable: 2,520 bytes in 3 blocks
==3361== suppressed: 0 bytes in 0 blocks
==3361== Rerun with --leak-check=full to see details of leaked memory
==3361==
==3361== For counts of detected and suppressed errors, rerun with: -v
==3361== Use --track-origins=yes to see where uninitialised values come from
==3361== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
Segmentation fault
It's an off-by-one array index.
Your while loop finishes with commands[i+1] being null. Then you pass it to splitter.
Pass commands[i] instead.
When strtok() finds a token, it changes the character immediately after the token into a \0, and then returns a pointer to the token.
Related
I have an error of Segmentation Fault caused by line
*head = malloc(sizeof(struct node)+1);'
I'm pretty sure that I used the construct node and the malloc in the same way in others cases where all worked fine.
The program print here1 and then a Core Dump happen.
this is my code:
struct node {
//int val ;
struct node * next;
unsigned char string[];
} ;
void init_list(struct node ** head) {
printf("here1 \n");
fflush(stdout);
*head = malloc(sizeof(struct node)+1);
printf("here2\n");
fflush(stdout);
if(!(*head)){
printf("error malloc \n");
fflush(stdout);
return ;
}
//(*head) -> val = -1;
(*head) -> next = NULL;
((*head) -> string)[0]= '\0';
return ;
}
int main(void) {
struct node ** head;
init_list(head) ;
printf("hereee\n");
fflush(stdout) ;
fini_list(head);
return 1;
}
This is what Valgrind returns me:
==6688== Memcheck, a memory error detector
==6688== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==6688== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==6688== Command: ./ex3
==6688==
heree
==6688== Invalid write of size 8
==6688== at 0x109267: init_list (ex3.c:43)
==6688== by 0x1092E9: main (ex3.c:66)
==6688== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==6688==
==6688==
==6688== Process terminating with default action of signal 11 (SIGSEGV)
==6688== Access not within mapped region at address 0x0
==6688== at 0x109267: init_list (ex3.c:43)
==6688== by 0x1092E9: main (ex3.c:66)
==6688== If you believe this happened as a result of a stack
==6688== overflow in your program's main thread (unlikely but
==6688== possible), you can try to increase the size of the
==6688== main thread stack using the --main-stacksize= flag.
==6688== The main thread stack size used in this run was 8388608 .
==6688==
==6688== HEAP SUMMARY:
==6688== in use at exit: 9 bytes in 1 blocks
==6688== total heap usage: 2 allocs, 1 frees, 1,033 bytes allocated
==6688==
==6688== LEAK SUMMARY:
==6688== definitely lost: 9 bytes in 1 blocks
==6688== indirectly lost: 0 bytes in 0 blocks
==6688== possibly lost: 0 bytes in 0 blocks
==6688== still reachable: 0 bytes in 0 blocks
==6688== suppressed: 0 bytes in 0 blocks
==6688== Rerun with --leak-check=full to see details of leaked memory
==6688==
==6688== For lists of detected and suppressed errors, rerun with: -s
==6688== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)
What I can't really understand is that I have used the same construct other programs and it that cases all worked fine.
So , what happens in the previous case ??
You pass an uninitialized pointer to your function:
int main(void) {
struct node ** head;
init_list(head) ;
As a result, head does not contain a valid address and dereferencing it in *head = ... causes your crash. It is not related to mallocat all.
That is not the way how this function should be used. You cannot pass the new pointer to the caller this way.
Try this instead:
int main(void) {
struct node *head = NULL;
init_list(&head) ;
I have created an array of threads and changing the global variables based on some conditions in the isSetFunc(). while returning the dynamically allocated character array and printing it in the main it only prints the last thread result in the main function and also while deallocating the memory inside the main function that was created inside the thread didn't get deallocated.
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#define BUFFER 10
int gset;
int gnot_set;
pthread_mutex_t glock;
void *SetFunc(void *args){
char* string = (char *)calloc(BUFFER, sizeof(char));
int* arg = (int *) args;
pthread_mutex_lock(&glock);
if(*arg < 4){
gset++;
strcpy(string, "True\n");
}
else{
gnot_set++;
strcpy(string, "False");
}
pthread_mutex_unlock(&glock);
return string;
}
int main()
{
int threadRes,
i = 0;
void* pResult;
pthread_t* thread;
pthread_mutex_init(&glock, NULL);
thread = (pthread_t *)malloc(sizeof(pthread_t)*(10));
while (i < 10)
{
threadRes = pthread_create(&(thread[i]), NULL, &isSetFunc, &i);
if(threadRes != 0){
fprintf(stderr, "Error occured while creating a thread\n");
return -1;
}
pthread_join(thread[i], &pResult);
i++;
}
printf("In main thread: %s\n", (char *)pResult);
printf("\ng_set = %d\ngnot_set = %d\n", gset, gnot_set);
pthread_mutex_destroy(&glock);
free(thread);
free(pResult);
return 0;
}
output
==387== Memcheck, a memory error detector
==387== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==387== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==387== Command: ./a.out
==387==
==387== error calling PR_SET_PTRACER, vgdb might block
In main thread: False
g_set = 4
gnot_set = 4
==387==
==387== HEAP SUMMARY:
==387== in use at exit: 70 bytes in 7 blocks
==387== total heap usage: 11 allocs, 4 frees, 4,512 bytes allocated
==387==
==387== LEAK SUMMARY:
==387== definitely lost: 70 bytes in 7 blocks
==387== indirectly lost: 0 bytes in 0 blocks
==387== possibly lost: 0 bytes in 0 blocks
==387== still reachable: 0 bytes in 0 blocks
==387== suppressed: 0 bytes in 0 blocks
==387== Rerun with --leak-check=full to see details of leaked memory
==387==
==387== For lists of detected and suppressed errors, rerun with: -s
==387== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Any help would be greatly appreciated and thanks.
Your threads are running one at a time, so you're only printing the final result after all threads are run.
The pthread_join function causes the calling thread to wait until the specified thread returns. Since you're calling pthread_join right after pthread_create, this means you create a thread, wait for it to finish, then create a new thread, etc.
The memory leak you're seeing is because every thread is returning malloced memory but you only free it once at the end of the program, so you're only freeing the last thread's result.
You want two loops: one for creating the threads and one for joining them. The second loop should call pthread_join, lock the mutux, print the values, unlock, then free the return value.
I using GNU MP to great an array of multi-precision integers. If I initialize, use and clean, all the main function, it works perfect, with no error. I've tried to create auxiliary functions to manage repetitive jobs: initialize an array and clean an array. Unfortunately it did not end up well, I'm getting a memory leak. I made a small example bellow reproducing the error behaviour:
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
mpz_t *start(int n)
{
mpz_t *c = malloc(n*sizeof(mpz_t));
for (int i=0; i<n; i++) mpz_init (c[i]);
for (int i=0; i<n; i++) mpz_set_ui (c[i], 1);
}
void finish(mpz_t *x, int n)
{
for (int i=0; i<n; i++) mpz_clear (x[i]);
free(x);
}
int main(int argc, char *argv[])
{
int n = 10;
mpz_t *c = start(n);
finish(c, n);
return 0;
}
The result of running the program is:
Segmentation fault (core dumped)
Bellow follows Valgrind analysis log:
==18807== Memcheck, a memory error detector
==18807== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==18807== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==18807== Command: ./test
==18807==
==18807== Invalid read of size 4
==18807== at 0x4887C60: __gmpz_clear (in /usr/lib/x86_64-linux-gnu/libgmp.so.10.3.2)
==18807== by 0x10928B: finish (test.c:14)
==18807== by 0x1092DF: main (test.c:22)
==18807== Address 0xa is not stack'd, malloc'd or (recently) free'd
==18807==
==18807==
==18807== Process terminating with default action of signal 11 (SIGSEGV)
==18807== Access not within mapped region at address 0xA
==18807== at 0x4887C60: __gmpz_clear (in /usr/lib/x86_64-linux-gnu/libgmp.so.10.3.2)
==18807== by 0x10928B: finish (test.c:14)
==18807== by 0x1092DF: main (test.c:22)
==18807== If you believe this happened as a result of a stack
==18807== overflow in your program's main thread (unlikely but
==18807== possible), you can try to increase the size of the
==18807== main thread stack using the --main-stacksize= flag.
==18807== The main thread stack size used in this run was 8388608.
==18807==
==18807== HEAP SUMMARY:
==18807== in use at exit: 240 bytes in 11 blocks
==18807== total heap usage: 11 allocs, 0 frees, 240 bytes allocated
==18807==
==18807== 240 (160 direct, 80 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==18807== at 0x483A7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==18807== by 0x1091E8: start (test.c:7)
==18807== by 0x1092CA: main (test.c:21)
==18807==
==18807== LEAK SUMMARY:
==18807== definitely lost: 160 bytes in 1 blocks
==18807== indirectly lost: 80 bytes in 10 blocks
==18807== possibly lost: 0 bytes in 0 blocks
==18807== still reachable: 0 bytes in 0 blocks
==18807== suppressed: 0 bytes in 0 blocks
==18807==
==18807== For lists of detected and suppressed errors, rerun with: -s
==18807== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)
What is wrong? How to fix it?
Flowing off the end of a value-returning function (except main) without a return statement is undefined behavior.
In your example, mpz_t *start(int n) doesn't actually return anything, which leads to UB.
I am very novice in working with malloc/realloc in C and so need some help. The following is short snippet of a big program where I intend to read a big (fasta) file almost 80000 line numbers and store the first line marked with > (name) and following line (sequence) in two separate arrays- fasta_name and fasta_seq. I have used a standard library which gives the output as a structure but I need to change it into arrays since later on the program I need to check input provided by the user with each of the fasta entries in the file..
The inputfile format is:
P21306\n
MSAWRKAGISYAAYLNVAAQAIRSSLKTELQTASVLNRSQTDAFYTQYKNGTAASEPTPITK\n
P38077\n
MLSRIVSNNATRSVMCHQAQVGILYKTNPVRTYATLKEVEMRLKSIKNIEKITKTMKIVASTRLSKAEKA\n
=======================
The code is:
KSEQ_INIT(gzFile, gzread) ///EXTERNAL LIBRARY FOR BIOLOGISTS READING FASTA FORMAT FILE///
int main(int argc,char *argv[])
{
char **fasta_name=(char **)malloc(sizeof(char *)*80000);
for(i=0;i<size;i++)
{
fasta_name[i]=(char*)malloc(sizeof(char)*50);
}
char **fasta_seq=(char**)malloc(sizeof(char *)*80000);
for(i=0;i<size;i++)
{
fasta_seq[i]=(char*)malloc(sizeof(char)*5000);
}
fpf = gzopen("fasta_seq_nr_uniprot.txt", "r");
seq = kseq_init(fpf);
while((l = kseq_read(seq)) >= 0)
{
strcpy(fasta_name[index1],seq->name.s);
strcpy(fasta_seq[index1],seq->seq.s);
index1++;
}
kseq_destroy(seq);
gzclose(fpf);
for(i=0;i<size;i++)
{
free(fasta_name[i]);
}
for(i=0;i<size;i++)
{
free(fasta_seq[i]);
}
free(fasta_name);
free(fasta_seq);
The program shows no compilation errors but the following memory errors and segmentation fault using Valgrind.
$ valgrind --track-origins=yes --leak-check=full ./Gwidd_uniprot_map2 xaa==3511== Memcheck, a memory error detector
==3511== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==3511== Using Valgrind-3.6.1 and LibVEX; rerun with -h for copyright info
==3511== Command: ./map2 xaa
==3511==
--3511-- ./map2:
--3511-- dSYM directory has wrong UUID; consider using --dsymutil=yes
Opening file xaa
==3511== Use of uninitialised value of size 8
==3511== at 0x100012C43: __strcpy_chk (mc_replace_strmem.c:893)
==3511== by 0x100001A78: __inline_strcpy_chk (in ./map2)
==3511== by 0x10000183E: main (in ./map2)
==3511== Uninitialised value was created by a heap allocation
==3511== at 0x100011345: malloc (vg_replace_malloc.c:236)
==3511== by 0x10000170C: main (in ./map2)
==3511==
==3511== Invalid write of size 1
==3511== at 0x100012C43: __strcpy_chk (mc_replace_strmem.c:893)
==3511== by 0x100001A78: __inline_strcpy_chk (in ./map2)
==3511== by 0x10000183E: main (in ./map2)
==3511== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==3511==
==3511==
==3511== Process terminating with default action of signal 11 (SIGSEGV)
==3511== Access not within mapped region at address 0x0
==3511== at 0x100012C43: __strcpy_chk (mc_replace_strmem.c:893)
==3511== by 0x100001A78: __inline_strcpy_chk (in ./map2)
==3511== by 0x10000183E: main (in ./map2)
==3511== If you believe this happened as a result of a stack
==3511== overflow in your program's main thread (unlikely but
==3511== possible), you can try to increase the size of the
==3511== main thread stack using the --main-stacksize= flag.
==3511== The main thread stack size used in this run was 8388608.
==3511==
==3511== HEAP SUMMARY:
==3511== in use at exit: 6,674,813 bytes in 3,664 blocks
==3511== total heap usage: 3,807 allocs, 143 frees, 6,698,108 bytes allocated
==3511==
==3511== LEAK SUMMARY:
==3511== definitely lost: 0 bytes in 0 blocks
==3511== indirectly lost: 0 bytes in 0 blocks
==3511== possibly lost: 0 bytes in 0 blocks
==3511== still reachable: 6,674,813 bytes in 3,664 blocks
==3511== suppressed: 0 bytes in 0 blocks
==3511== Reachable blocks (those to which a pointer was found) are not shown.
==3511== To see them, rerun with: --leak-check=full --show-reachable=yes
==3511==
==3511== For counts of detected and suppressed errors, rerun with: -v
==3511== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
Segmentation fault
CODE EDITED AS:
char **fasta_name=(char **)malloc(sizeof(char *)*80000);
if(fasta_name == NULL)
{
printf("Unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
for(i=0;i<size;i++)
{
fasta_name[i]=(char*)malloc(sizeof(char)*50);
if(fasta_name[i] == NULL)
{
printf("Unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
}
char **fasta_seq=(char**)malloc(sizeof(char *)*80000);
if(fasta_seq == NULL)
{
printf("Unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
for(i=0;i<size;i++)
{
fasta_seq[i]=(char*)malloc(sizeof(char)*5000);
if(fasta_seq[i] == NULL)
{
printf("Unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
}
fpf = gzopen("fasta_seq_nr_uniprot.txt", "r");
seq = kseq_init(fpf);
while((l = kseq_read(seq)) >= 0)
{
strcpy(fasta_name[index1],seq->name.s);
strcpy(fasta_seq[index1],seq->seq.s);
index1++;
}
kseq_destroy(seq);
gzclose(fpf);
Based on the error Access not within mapped region at address, I would say that you are accessing memory that's out of bounds, causing your segmentation fault. Check that malloc() doesn't return NULL to you after calling it, otherwise you risk accessing memory you don't actually own.
Do this after every single malloc() call. For example:
int *i = (int *) malloc(sizeof(int));
if(!i){
fprintf(stderr, "Something went wrong with malloc(), exiting...\n");
exit(1);
}
Another thing to check is to see if index1 is out of bounds of your allocations. I don't see where it's declared or initialized. Is it possible that your allocation for fasta_name and others is too small, given that you read information using a while loop that keeps incrementing the index?
I am running breadth first search and bellman ford algorithms on large sets of graph data in the format (u, v, weight) from an input file.
I initialize in the breadth first search, that all vertex's should be marked 0 for unvisited.
Later in the program, since I am calling BFS after every time I add an edge, rather than at the end of the program all together (it's part of a research project on bellman ford and BFS even though it doesn't quite make sense) I reinitialize the vertex array to unvisited.
However, I am getting a segmentation fault when I run larger sets it seems when I reinitialize the vertex array. I make the assumption about larger sets because I have a few smaller sets of test data going from 8 vertices, to 10, then at 100 and larger it fails.
Here is how I initialize at the very beginning of the program:
for(i=0;i<numberVertices;i++)
{
vertexArray[i].v = i+1;
vertexArray[i].adj = NULL;
vertexArray[i].marked = 0;
if(i==0)
{
vertexArray[i].weight = 0;
}
else{
vertexArray[i].weight = 10000;
}
}
And here is how I reinitialize at the end of a while loop set to break when it reaches the end of the file directly after BFS finishes:
BFS(q, u)
for(i=0;i<numberVertices;i++)
{
vertexArray[i].marked = 0;
}
Like I said it seems to work for smaller data sets, but I do not understand why when I reinitialize it seems to seg fault.
Please let me know your thoughts and suggestions!
Valgrind Output On An Example Case:
==6634== Memcheck, a memory error detector
==6634== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==6634== Using Valgrind-3.6.0 and LibVEX; rerun with -h for copyright info
==6634== Command: ./a.out 100S.txt
==6634==
==6634== Conditional jump or move depends on uninitialised value(s)
==6634== at 0x400C13: checkonqueue (bfs.c:160)
==6634== by 0x400B7F: BFS (bfs.c:142)
==6634== by 0x40094A: main (bfs.c:103)
==6634==
==6634== Invalid write of size 4
==6634== at 0x40096E: main (bfs.c:107)
==6634== Address 0x4d00000041 is not stack'd, malloc'd or (recently) free'd
==6634==
==6634==
==6634== Process terminating with default action of signal 11 (SIGSEGV)
==6634== Access not within mapped region at address 0x4D00000041
==6634== at 0x40096E: main (bfs.c:107)
==6634== If you believe this happened as a result of a stack
==6634== overflow in your program's main thread (unlikely but
==6634== possible), you can try to increase the size of the
==6634== main thread stack using the --main-stacksize= flag.
==6634== The main thread stack size used in this run was 10485760.
==6634==
==6634== HEAP SUMMARY:
==6634== in use at exit: 3,448 bytes in 181 blocks
==6634== total heap usage: 181 allocs, 0 frees, 3,448 bytes allocated
==6634==
==6634== LEAK SUMMARY:
==6634== definitely lost: 0 bytes in 0 blocks
==6634== indirectly lost: 0 bytes in 0 blocks
==6634== possibly lost: 0 bytes in 0 blocks
==6634== still reachable: 3,448 bytes in 181 blocks
==6634== suppressed: 0 bytes in 0 blocks
==6634== Reachable blocks (those to which a pointer was found) are not shown.
==6634== To see them, rerun with: --leak-check=full --show-reachable=yes
==6634==
==6634== For counts of detected and suppressed errors, rerun with: -v
==6634== Use --track-origins=yes to see where uninitialised values come from
==6634== ERROR SUMMARY: 16120 errors from 2 contexts (suppressed: 6 from 6)
Segmentation fault (core dumped)
check on queue function:
int checkonqueue(int * q, int value)
{
int i = 0;
for(i=0;i < max;i++)
{
if(q[i] == value)
{
return 1;
}
}
return 0;
}
line 160 is the line of the if condition