bkepley
bkepley

Reputation: 81

Why does this c-code get a segmentation fault in strcpy?

Why does this code at the strcpy() give me a segmentation fault? I am using GNU and when the code reaches the strcpy it fails for a segmentation fault.

#include<stdio.h>
#include<string.h>
#include<assert.h>

void PrintString(char *buff);
int main()
{
    char *buffPtr = malloc(128);

    assert(&buffPtr != NULL);

    memset(&buffPtr, 0, sizeof(buffPtr));

    strcpy(buffPtr,  "This is my string");

    free(buffPtr);
    return 0;
}

Upvotes: 0

Views: 82

Answers (1)

interjay
interjay

Reputation: 110148

The memset will overwrite the pointer instead of the memory it points to. It should be:

memset(buffPtr, 0, 128);

I removed the ampersand and set the correct size (sizeof(buffPtr) is the size of a pointer, not the size that was allocated).

You should also change the assert to check buffPtr != NULL without the ampersand (&buffPtr will never be null). And using assert isn't really correct here because it may do nothing in a release build.

Upvotes: 5

Related Questions