andreihondrari
andreihondrari

Reputation: 5833

MEMCPY segmentation fault when trying to copy into structure element

The code is: (I've marked the faulty line with a comment)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>

typedef struct stack_node_type{
    int *nr;
    char *string;
struct stack_node_type *next;
} SNODE;

SNODE * pushStack(SNODE **stack, int *nr, char *string){
SNODE *snode=NULL;
if(nr!=NULL){
    snode = (SNODE *) malloc(sizeof(SNODE));
    aux=snode->nr;
    printf("%d\n", *nr);
    memcpy(snode->nr, nr, sizeof(int)); //THIS IS THE FAULTY LINE
    if(*(&stack)!=NULL){
        snode->next=&(**stack);
    }
    else{
        snode->next=NULL;
    }
    if(string!=NULL){
        snode->string=&(*string);
    }
}
else{
    if(string!=NULL){
        snode = (SNODE *) malloc(sizeof(SNODE));
        if(*(&stack)!=NULL){
            snode->next=&(**stack);
        }
        else{
            snode->next=NULL;
        }
        snode->string=&(*string);
    }
}
if(snode!=NULL){
    return &(*snode);
}
else{
    return &(**stack);
}
}

SNODE * popStack(SNODE **stack, SNODE *pop){
SNODE *snode=NULL;
snode=&(**stack);
if(snode!=NULL){
    if(snode->nr!=NULL){
        pop->nr=(int *) malloc(sizeof(int));
        * (pop->nr) = * (snode->nr);
    }
    if(snode->string!=NULL){
        int strdim = strlen(snode->string);
        pop->string=(char *) malloc(strdim*sizeof(char));
        strcpy(pop->string, snode->string);
    }
    SNODE *to_del=snode;
    snode=snode->next;
    free(to_del);
}
return &(*snode);
}

int main()
{
SNODE *stack=NULL;
SNODE pop;
int nr;
nr=123;
stack=pushStack(&stack, &nr, "banane");
nr=819;
stack=pushStack(&stack, &nr, "portocale");
while(stack!=NULL){
    stack=popStack(&stack, &pop);
    printf("POP: %d, \"%s\"\n", *(pop.nr), pop.string);
}
    return 0;
}

Restating the faulty line:

memcpy(snode->nr, nr, sizeof(int)); //THIS IS THE FAULTY LINE

Memcpy should crack when unavailable memory is being accesed or the source and destination memory blocks overlap, so as far as I'm concerned, none of these problems seem to be valid. Why does it crack?

Upvotes: 1

Views: 1072

Answers (1)

cnicutar
cnicutar

Reputation: 182689

You allocated memory for the structure but didn't allocate for the members themselves.

Try:

snode = (SNODE *) malloc(sizeof(SNODE));
snode->nr = malloc(sizeof(int));

But if I were you I would change the structure:

struct stack_node_type{
    int nr;
    char *string;
};

memcpy(&snode->nr, nr, sizeof(nr));

Upvotes: 4

Related Questions